1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.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/Analysis/Analyses/FormatString.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.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 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
195   if (checkArgCount(S, TheCall, 3))
196     return true;
197 
198   // First two arguments should be integers.
199   for (unsigned I = 0; I < 2; ++I) {
200     ExprResult Arg = TheCall->getArg(I);
201     QualType Ty = Arg.get()->getType();
202     if (!Ty->isIntegerType()) {
203       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
204           << Ty << Arg.get()->getSourceRange();
205       return true;
206     }
207     InitializedEntity Entity = InitializedEntity::InitializeParameter(
208         S.getASTContext(), Ty, /*consume*/ false);
209     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
210     if (Arg.isInvalid())
211       return true;
212     TheCall->setArg(I, Arg.get());
213   }
214 
215   // Third argument should be a pointer to a non-const integer.
216   // IRGen correctly handles volatile, restrict, and address spaces, and
217   // the other qualifiers aren't possible.
218   {
219     ExprResult Arg = TheCall->getArg(2);
220     QualType Ty = Arg.get()->getType();
221     const auto *PtrTy = Ty->getAs<PointerType>();
222     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
223           !PtrTy->getPointeeType().isConstQualified())) {
224       S.Diag(Arg.get()->getBeginLoc(),
225              diag::err_overflow_builtin_must_be_ptr_int)
226           << Ty << Arg.get()->getSourceRange();
227       return true;
228     }
229     InitializedEntity Entity = InitializedEntity::InitializeParameter(
230         S.getASTContext(), Ty, /*consume*/ false);
231     Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
232     if (Arg.isInvalid())
233       return true;
234     TheCall->setArg(2, Arg.get());
235   }
236   return false;
237 }
238 
239 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
240                                   CallExpr *TheCall, unsigned SizeIdx,
241                                   unsigned DstSizeIdx,
242                                   StringRef LikelyMacroName) {
243   if (TheCall->getNumArgs() <= SizeIdx ||
244       TheCall->getNumArgs() <= DstSizeIdx)
245     return;
246 
247   const Expr *SizeArg = TheCall->getArg(SizeIdx);
248   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
249 
250   llvm::APSInt Size, DstSize;
251 
252   // find out if both sizes are known at compile time
253   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
254       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
255     return;
256 
257   if (Size.ule(DstSize))
258     return;
259 
260   // Confirmed overflow, so generate the diagnostic.
261   StringRef FunctionName = FDecl->getName();
262   SourceLocation SL = TheCall->getBeginLoc();
263   SourceManager &SM = S.getSourceManager();
264   // If we're in an expansion of a macro whose name corresponds to this builtin,
265   // use the simple macro name and location.
266   if (SL.isMacroID() && Lexer::getImmediateMacroName(SL, SM, S.getLangOpts()) ==
267                             LikelyMacroName) {
268     FunctionName = LikelyMacroName;
269     SL = SM.getImmediateMacroCallerLoc(SL);
270   }
271 
272   S.Diag(SL, diag::warn_memcpy_chk_overflow)
273       << FunctionName << DstSize.toString(/*Radix=*/10)
274       << Size.toString(/*Radix=*/10);
275 }
276 
277 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
278   if (checkArgCount(S, BuiltinCall, 2))
279     return true;
280 
281   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
282   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
283   Expr *Call = BuiltinCall->getArg(0);
284   Expr *Chain = BuiltinCall->getArg(1);
285 
286   if (Call->getStmtClass() != Stmt::CallExprClass) {
287     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
288         << Call->getSourceRange();
289     return true;
290   }
291 
292   auto CE = cast<CallExpr>(Call);
293   if (CE->getCallee()->getType()->isBlockPointerType()) {
294     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
295         << Call->getSourceRange();
296     return true;
297   }
298 
299   const Decl *TargetDecl = CE->getCalleeDecl();
300   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
301     if (FD->getBuiltinID()) {
302       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
303           << Call->getSourceRange();
304       return true;
305     }
306 
307   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
308     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
309         << Call->getSourceRange();
310     return true;
311   }
312 
313   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
314   if (ChainResult.isInvalid())
315     return true;
316   if (!ChainResult.get()->getType()->isPointerType()) {
317     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
318         << Chain->getSourceRange();
319     return true;
320   }
321 
322   QualType ReturnTy = CE->getCallReturnType(S.Context);
323   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
324   QualType BuiltinTy = S.Context.getFunctionType(
325       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
326   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
327 
328   Builtin =
329       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
330 
331   BuiltinCall->setType(CE->getType());
332   BuiltinCall->setValueKind(CE->getValueKind());
333   BuiltinCall->setObjectKind(CE->getObjectKind());
334   BuiltinCall->setCallee(Builtin);
335   BuiltinCall->setArg(1, ChainResult.get());
336 
337   return false;
338 }
339 
340 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
341                                      Scope::ScopeFlags NeededScopeFlags,
342                                      unsigned DiagID) {
343   // Scopes aren't available during instantiation. Fortunately, builtin
344   // functions cannot be template args so they cannot be formed through template
345   // instantiation. Therefore checking once during the parse is sufficient.
346   if (SemaRef.inTemplateInstantiation())
347     return false;
348 
349   Scope *S = SemaRef.getCurScope();
350   while (S && !S->isSEHExceptScope())
351     S = S->getParent();
352   if (!S || !(S->getFlags() & NeededScopeFlags)) {
353     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
354     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
355         << DRE->getDecl()->getIdentifier();
356     return true;
357   }
358 
359   return false;
360 }
361 
362 static inline bool isBlockPointer(Expr *Arg) {
363   return Arg->getType()->isBlockPointerType();
364 }
365 
366 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
367 /// void*, which is a requirement of device side enqueue.
368 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
369   const BlockPointerType *BPT =
370       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
371   ArrayRef<QualType> Params =
372       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
373   unsigned ArgCounter = 0;
374   bool IllegalParams = false;
375   // Iterate through the block parameters until either one is found that is not
376   // a local void*, or the block is valid.
377   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
378        I != E; ++I, ++ArgCounter) {
379     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
380         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
381             LangAS::opencl_local) {
382       // Get the location of the error. If a block literal has been passed
383       // (BlockExpr) then we can point straight to the offending argument,
384       // else we just point to the variable reference.
385       SourceLocation ErrorLoc;
386       if (isa<BlockExpr>(BlockArg)) {
387         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
388         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
389       } else if (isa<DeclRefExpr>(BlockArg)) {
390         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
391       }
392       S.Diag(ErrorLoc,
393              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
394       IllegalParams = true;
395     }
396   }
397 
398   return IllegalParams;
399 }
400 
401 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
402   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
403     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
404         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
405     return true;
406   }
407   return false;
408 }
409 
410 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
411   if (checkArgCount(S, TheCall, 2))
412     return true;
413 
414   if (checkOpenCLSubgroupExt(S, TheCall))
415     return true;
416 
417   // First argument is an ndrange_t type.
418   Expr *NDRangeArg = TheCall->getArg(0);
419   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
420     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
421         << TheCall->getDirectCallee() << "'ndrange_t'";
422     return true;
423   }
424 
425   Expr *BlockArg = TheCall->getArg(1);
426   if (!isBlockPointer(BlockArg)) {
427     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
428         << TheCall->getDirectCallee() << "block";
429     return true;
430   }
431   return checkOpenCLBlockArgs(S, BlockArg);
432 }
433 
434 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
435 /// get_kernel_work_group_size
436 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
437 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
438   if (checkArgCount(S, TheCall, 1))
439     return true;
440 
441   Expr *BlockArg = TheCall->getArg(0);
442   if (!isBlockPointer(BlockArg)) {
443     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
444         << TheCall->getDirectCallee() << "block";
445     return true;
446   }
447   return checkOpenCLBlockArgs(S, BlockArg);
448 }
449 
450 /// Diagnose integer type and any valid implicit conversion to it.
451 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
452                                       const QualType &IntType);
453 
454 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
455                                             unsigned Start, unsigned End) {
456   bool IllegalParams = false;
457   for (unsigned I = Start; I <= End; ++I)
458     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
459                                               S.Context.getSizeType());
460   return IllegalParams;
461 }
462 
463 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
464 /// 'local void*' parameter of passed block.
465 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
466                                            Expr *BlockArg,
467                                            unsigned NumNonVarArgs) {
468   const BlockPointerType *BPT =
469       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
470   unsigned NumBlockParams =
471       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
472   unsigned TotalNumArgs = TheCall->getNumArgs();
473 
474   // For each argument passed to the block, a corresponding uint needs to
475   // be passed to describe the size of the local memory.
476   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
477     S.Diag(TheCall->getBeginLoc(),
478            diag::err_opencl_enqueue_kernel_local_size_args);
479     return true;
480   }
481 
482   // Check that the sizes of the local memory are specified by integers.
483   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
484                                          TotalNumArgs - 1);
485 }
486 
487 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
488 /// overload formats specified in Table 6.13.17.1.
489 /// int enqueue_kernel(queue_t queue,
490 ///                    kernel_enqueue_flags_t flags,
491 ///                    const ndrange_t ndrange,
492 ///                    void (^block)(void))
493 /// int enqueue_kernel(queue_t queue,
494 ///                    kernel_enqueue_flags_t flags,
495 ///                    const ndrange_t ndrange,
496 ///                    uint num_events_in_wait_list,
497 ///                    clk_event_t *event_wait_list,
498 ///                    clk_event_t *event_ret,
499 ///                    void (^block)(void))
500 /// int enqueue_kernel(queue_t queue,
501 ///                    kernel_enqueue_flags_t flags,
502 ///                    const ndrange_t ndrange,
503 ///                    void (^block)(local void*, ...),
504 ///                    uint size0, ...)
505 /// int enqueue_kernel(queue_t queue,
506 ///                    kernel_enqueue_flags_t flags,
507 ///                    const ndrange_t ndrange,
508 ///                    uint num_events_in_wait_list,
509 ///                    clk_event_t *event_wait_list,
510 ///                    clk_event_t *event_ret,
511 ///                    void (^block)(local void*, ...),
512 ///                    uint size0, ...)
513 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
514   unsigned NumArgs = TheCall->getNumArgs();
515 
516   if (NumArgs < 4) {
517     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
518     return true;
519   }
520 
521   Expr *Arg0 = TheCall->getArg(0);
522   Expr *Arg1 = TheCall->getArg(1);
523   Expr *Arg2 = TheCall->getArg(2);
524   Expr *Arg3 = TheCall->getArg(3);
525 
526   // First argument always needs to be a queue_t type.
527   if (!Arg0->getType()->isQueueT()) {
528     S.Diag(TheCall->getArg(0)->getBeginLoc(),
529            diag::err_opencl_builtin_expected_type)
530         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
531     return true;
532   }
533 
534   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
535   if (!Arg1->getType()->isIntegerType()) {
536     S.Diag(TheCall->getArg(1)->getBeginLoc(),
537            diag::err_opencl_builtin_expected_type)
538         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
539     return true;
540   }
541 
542   // Third argument is always an ndrange_t type.
543   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
544     S.Diag(TheCall->getArg(2)->getBeginLoc(),
545            diag::err_opencl_builtin_expected_type)
546         << TheCall->getDirectCallee() << "'ndrange_t'";
547     return true;
548   }
549 
550   // With four arguments, there is only one form that the function could be
551   // called in: no events and no variable arguments.
552   if (NumArgs == 4) {
553     // check that the last argument is the right block type.
554     if (!isBlockPointer(Arg3)) {
555       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
556           << TheCall->getDirectCallee() << "block";
557       return true;
558     }
559     // we have a block type, check the prototype
560     const BlockPointerType *BPT =
561         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
562     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
563       S.Diag(Arg3->getBeginLoc(),
564              diag::err_opencl_enqueue_kernel_blocks_no_args);
565       return true;
566     }
567     return false;
568   }
569   // we can have block + varargs.
570   if (isBlockPointer(Arg3))
571     return (checkOpenCLBlockArgs(S, Arg3) ||
572             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
573   // last two cases with either exactly 7 args or 7 args and varargs.
574   if (NumArgs >= 7) {
575     // check common block argument.
576     Expr *Arg6 = TheCall->getArg(6);
577     if (!isBlockPointer(Arg6)) {
578       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
579           << TheCall->getDirectCallee() << "block";
580       return true;
581     }
582     if (checkOpenCLBlockArgs(S, Arg6))
583       return true;
584 
585     // Forth argument has to be any integer type.
586     if (!Arg3->getType()->isIntegerType()) {
587       S.Diag(TheCall->getArg(3)->getBeginLoc(),
588              diag::err_opencl_builtin_expected_type)
589           << TheCall->getDirectCallee() << "integer";
590       return true;
591     }
592     // check remaining common arguments.
593     Expr *Arg4 = TheCall->getArg(4);
594     Expr *Arg5 = TheCall->getArg(5);
595 
596     // Fifth argument is always passed as a pointer to clk_event_t.
597     if (!Arg4->isNullPointerConstant(S.Context,
598                                      Expr::NPC_ValueDependentIsNotNull) &&
599         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
600       S.Diag(TheCall->getArg(4)->getBeginLoc(),
601              diag::err_opencl_builtin_expected_type)
602           << TheCall->getDirectCallee()
603           << S.Context.getPointerType(S.Context.OCLClkEventTy);
604       return true;
605     }
606 
607     // Sixth argument is always passed as a pointer to clk_event_t.
608     if (!Arg5->isNullPointerConstant(S.Context,
609                                      Expr::NPC_ValueDependentIsNotNull) &&
610         !(Arg5->getType()->isPointerType() &&
611           Arg5->getType()->getPointeeType()->isClkEventT())) {
612       S.Diag(TheCall->getArg(5)->getBeginLoc(),
613              diag::err_opencl_builtin_expected_type)
614           << TheCall->getDirectCallee()
615           << S.Context.getPointerType(S.Context.OCLClkEventTy);
616       return true;
617     }
618 
619     if (NumArgs == 7)
620       return false;
621 
622     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
623   }
624 
625   // None of the specific case has been detected, give generic error
626   S.Diag(TheCall->getBeginLoc(),
627          diag::err_opencl_enqueue_kernel_incorrect_args);
628   return true;
629 }
630 
631 /// Returns OpenCL access qual.
632 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
633     return D->getAttr<OpenCLAccessAttr>();
634 }
635 
636 /// Returns true if pipe element type is different from the pointer.
637 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
638   const Expr *Arg0 = Call->getArg(0);
639   // First argument type should always be pipe.
640   if (!Arg0->getType()->isPipeType()) {
641     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
642         << Call->getDirectCallee() << Arg0->getSourceRange();
643     return true;
644   }
645   OpenCLAccessAttr *AccessQual =
646       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
647   // Validates the access qualifier is compatible with the call.
648   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
649   // read_only and write_only, and assumed to be read_only if no qualifier is
650   // specified.
651   switch (Call->getDirectCallee()->getBuiltinID()) {
652   case Builtin::BIread_pipe:
653   case Builtin::BIreserve_read_pipe:
654   case Builtin::BIcommit_read_pipe:
655   case Builtin::BIwork_group_reserve_read_pipe:
656   case Builtin::BIsub_group_reserve_read_pipe:
657   case Builtin::BIwork_group_commit_read_pipe:
658   case Builtin::BIsub_group_commit_read_pipe:
659     if (!(!AccessQual || AccessQual->isReadOnly())) {
660       S.Diag(Arg0->getBeginLoc(),
661              diag::err_opencl_builtin_pipe_invalid_access_modifier)
662           << "read_only" << Arg0->getSourceRange();
663       return true;
664     }
665     break;
666   case Builtin::BIwrite_pipe:
667   case Builtin::BIreserve_write_pipe:
668   case Builtin::BIcommit_write_pipe:
669   case Builtin::BIwork_group_reserve_write_pipe:
670   case Builtin::BIsub_group_reserve_write_pipe:
671   case Builtin::BIwork_group_commit_write_pipe:
672   case Builtin::BIsub_group_commit_write_pipe:
673     if (!(AccessQual && AccessQual->isWriteOnly())) {
674       S.Diag(Arg0->getBeginLoc(),
675              diag::err_opencl_builtin_pipe_invalid_access_modifier)
676           << "write_only" << Arg0->getSourceRange();
677       return true;
678     }
679     break;
680   default:
681     break;
682   }
683   return false;
684 }
685 
686 /// Returns true if pipe element type is different from the pointer.
687 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
688   const Expr *Arg0 = Call->getArg(0);
689   const Expr *ArgIdx = Call->getArg(Idx);
690   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
691   const QualType EltTy = PipeTy->getElementType();
692   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
693   // The Idx argument should be a pointer and the type of the pointer and
694   // the type of pipe element should also be the same.
695   if (!ArgTy ||
696       !S.Context.hasSameType(
697           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
698     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
699         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
700         << ArgIdx->getType() << ArgIdx->getSourceRange();
701     return true;
702   }
703   return false;
704 }
705 
706 // Performs semantic analysis for the read/write_pipe call.
707 // \param S Reference to the semantic analyzer.
708 // \param Call A pointer to the builtin call.
709 // \return True if a semantic error has been found, false otherwise.
710 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
711   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
712   // functions have two forms.
713   switch (Call->getNumArgs()) {
714   case 2:
715     if (checkOpenCLPipeArg(S, Call))
716       return true;
717     // The call with 2 arguments should be
718     // read/write_pipe(pipe T, T*).
719     // Check packet type T.
720     if (checkOpenCLPipePacketType(S, Call, 1))
721       return true;
722     break;
723 
724   case 4: {
725     if (checkOpenCLPipeArg(S, Call))
726       return true;
727     // The call with 4 arguments should be
728     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
729     // Check reserve_id_t.
730     if (!Call->getArg(1)->getType()->isReserveIDT()) {
731       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
732           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
733           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
734       return true;
735     }
736 
737     // Check the index.
738     const Expr *Arg2 = Call->getArg(2);
739     if (!Arg2->getType()->isIntegerType() &&
740         !Arg2->getType()->isUnsignedIntegerType()) {
741       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
742           << Call->getDirectCallee() << S.Context.UnsignedIntTy
743           << Arg2->getType() << Arg2->getSourceRange();
744       return true;
745     }
746 
747     // Check packet type T.
748     if (checkOpenCLPipePacketType(S, Call, 3))
749       return true;
750   } break;
751   default:
752     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
753         << Call->getDirectCallee() << Call->getSourceRange();
754     return true;
755   }
756 
757   return false;
758 }
759 
760 // Performs a semantic analysis on the {work_group_/sub_group_
761 //        /_}reserve_{read/write}_pipe
762 // \param S Reference to the semantic analyzer.
763 // \param Call The call to the builtin function to be analyzed.
764 // \return True if a semantic error was found, false otherwise.
765 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
766   if (checkArgCount(S, Call, 2))
767     return true;
768 
769   if (checkOpenCLPipeArg(S, Call))
770     return true;
771 
772   // Check the reserve size.
773   if (!Call->getArg(1)->getType()->isIntegerType() &&
774       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
775     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
776         << Call->getDirectCallee() << S.Context.UnsignedIntTy
777         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
778     return true;
779   }
780 
781   // Since return type of reserve_read/write_pipe built-in function is
782   // reserve_id_t, which is not defined in the builtin def file , we used int
783   // as return type and need to override the return type of these functions.
784   Call->setType(S.Context.OCLReserveIDTy);
785 
786   return false;
787 }
788 
789 // Performs a semantic analysis on {work_group_/sub_group_
790 //        /_}commit_{read/write}_pipe
791 // \param S Reference to the semantic analyzer.
792 // \param Call The call to the builtin function to be analyzed.
793 // \return True if a semantic error was found, false otherwise.
794 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
795   if (checkArgCount(S, Call, 2))
796     return true;
797 
798   if (checkOpenCLPipeArg(S, Call))
799     return true;
800 
801   // Check reserve_id_t.
802   if (!Call->getArg(1)->getType()->isReserveIDT()) {
803     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
804         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
805         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
806     return true;
807   }
808 
809   return false;
810 }
811 
812 // Performs a semantic analysis on the call to built-in Pipe
813 //        Query Functions.
814 // \param S Reference to the semantic analyzer.
815 // \param Call The call to the builtin function to be analyzed.
816 // \return True if a semantic error was found, false otherwise.
817 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
818   if (checkArgCount(S, Call, 1))
819     return true;
820 
821   if (!Call->getArg(0)->getType()->isPipeType()) {
822     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
823         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
824     return true;
825   }
826 
827   return false;
828 }
829 
830 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
831 // Performs semantic analysis for the to_global/local/private call.
832 // \param S Reference to the semantic analyzer.
833 // \param BuiltinID ID of the builtin function.
834 // \param Call A pointer to the builtin call.
835 // \return True if a semantic error has been found, false otherwise.
836 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
837                                     CallExpr *Call) {
838   if (Call->getNumArgs() != 1) {
839     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
840         << Call->getDirectCallee() << Call->getSourceRange();
841     return true;
842   }
843 
844   auto RT = Call->getArg(0)->getType();
845   if (!RT->isPointerType() || RT->getPointeeType()
846       .getAddressSpace() == LangAS::opencl_constant) {
847     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
848         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
849     return true;
850   }
851 
852   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
853     S.Diag(Call->getArg(0)->getBeginLoc(),
854            diag::warn_opencl_generic_address_space_arg)
855         << Call->getDirectCallee()->getNameInfo().getAsString()
856         << Call->getArg(0)->getSourceRange();
857   }
858 
859   RT = RT->getPointeeType();
860   auto Qual = RT.getQualifiers();
861   switch (BuiltinID) {
862   case Builtin::BIto_global:
863     Qual.setAddressSpace(LangAS::opencl_global);
864     break;
865   case Builtin::BIto_local:
866     Qual.setAddressSpace(LangAS::opencl_local);
867     break;
868   case Builtin::BIto_private:
869     Qual.setAddressSpace(LangAS::opencl_private);
870     break;
871   default:
872     llvm_unreachable("Invalid builtin function");
873   }
874   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
875       RT.getUnqualifiedType(), Qual)));
876 
877   return false;
878 }
879 
880 // Emit an error and return true if the current architecture is not in the list
881 // of supported architectures.
882 static bool
883 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
884                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
885   llvm::Triple::ArchType CurArch =
886       S.getASTContext().getTargetInfo().getTriple().getArch();
887   if (llvm::is_contained(SupportedArchs, CurArch))
888     return false;
889   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
890       << TheCall->getSourceRange();
891   return true;
892 }
893 
894 ExprResult
895 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
896                                CallExpr *TheCall) {
897   ExprResult TheCallResult(TheCall);
898 
899   // Find out if any arguments are required to be integer constant expressions.
900   unsigned ICEArguments = 0;
901   ASTContext::GetBuiltinTypeError Error;
902   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
903   if (Error != ASTContext::GE_None)
904     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
905 
906   // If any arguments are required to be ICE's, check and diagnose.
907   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
908     // Skip arguments not required to be ICE's.
909     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
910 
911     llvm::APSInt Result;
912     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
913       return true;
914     ICEArguments &= ~(1 << ArgNo);
915   }
916 
917   switch (BuiltinID) {
918   case Builtin::BI__builtin___CFStringMakeConstantString:
919     assert(TheCall->getNumArgs() == 1 &&
920            "Wrong # arguments to builtin CFStringMakeConstantString");
921     if (CheckObjCString(TheCall->getArg(0)))
922       return ExprError();
923     break;
924   case Builtin::BI__builtin_ms_va_start:
925   case Builtin::BI__builtin_stdarg_start:
926   case Builtin::BI__builtin_va_start:
927     if (SemaBuiltinVAStart(BuiltinID, TheCall))
928       return ExprError();
929     break;
930   case Builtin::BI__va_start: {
931     switch (Context.getTargetInfo().getTriple().getArch()) {
932     case llvm::Triple::arm:
933     case llvm::Triple::thumb:
934       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
935         return ExprError();
936       break;
937     default:
938       if (SemaBuiltinVAStart(BuiltinID, TheCall))
939         return ExprError();
940       break;
941     }
942     break;
943   }
944 
945   // The acquire, release, and no fence variants are ARM and AArch64 only.
946   case Builtin::BI_interlockedbittestandset_acq:
947   case Builtin::BI_interlockedbittestandset_rel:
948   case Builtin::BI_interlockedbittestandset_nf:
949   case Builtin::BI_interlockedbittestandreset_acq:
950   case Builtin::BI_interlockedbittestandreset_rel:
951   case Builtin::BI_interlockedbittestandreset_nf:
952     if (CheckBuiltinTargetSupport(
953             *this, BuiltinID, TheCall,
954             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
955       return ExprError();
956     break;
957 
958   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
959   case Builtin::BI_bittest64:
960   case Builtin::BI_bittestandcomplement64:
961   case Builtin::BI_bittestandreset64:
962   case Builtin::BI_bittestandset64:
963   case Builtin::BI_interlockedbittestandreset64:
964   case Builtin::BI_interlockedbittestandset64:
965     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
966                                   {llvm::Triple::x86_64, llvm::Triple::arm,
967                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
968       return ExprError();
969     break;
970 
971   case Builtin::BI__builtin_isgreater:
972   case Builtin::BI__builtin_isgreaterequal:
973   case Builtin::BI__builtin_isless:
974   case Builtin::BI__builtin_islessequal:
975   case Builtin::BI__builtin_islessgreater:
976   case Builtin::BI__builtin_isunordered:
977     if (SemaBuiltinUnorderedCompare(TheCall))
978       return ExprError();
979     break;
980   case Builtin::BI__builtin_fpclassify:
981     if (SemaBuiltinFPClassification(TheCall, 6))
982       return ExprError();
983     break;
984   case Builtin::BI__builtin_isfinite:
985   case Builtin::BI__builtin_isinf:
986   case Builtin::BI__builtin_isinf_sign:
987   case Builtin::BI__builtin_isnan:
988   case Builtin::BI__builtin_isnormal:
989   case Builtin::BI__builtin_signbit:
990   case Builtin::BI__builtin_signbitf:
991   case Builtin::BI__builtin_signbitl:
992     if (SemaBuiltinFPClassification(TheCall, 1))
993       return ExprError();
994     break;
995   case Builtin::BI__builtin_shufflevector:
996     return SemaBuiltinShuffleVector(TheCall);
997     // TheCall will be freed by the smart pointer here, but that's fine, since
998     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
999   case Builtin::BI__builtin_prefetch:
1000     if (SemaBuiltinPrefetch(TheCall))
1001       return ExprError();
1002     break;
1003   case Builtin::BI__builtin_alloca_with_align:
1004     if (SemaBuiltinAllocaWithAlign(TheCall))
1005       return ExprError();
1006     break;
1007   case Builtin::BI__assume:
1008   case Builtin::BI__builtin_assume:
1009     if (SemaBuiltinAssume(TheCall))
1010       return ExprError();
1011     break;
1012   case Builtin::BI__builtin_assume_aligned:
1013     if (SemaBuiltinAssumeAligned(TheCall))
1014       return ExprError();
1015     break;
1016   case Builtin::BI__builtin_object_size:
1017     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1018       return ExprError();
1019     break;
1020   case Builtin::BI__builtin_longjmp:
1021     if (SemaBuiltinLongjmp(TheCall))
1022       return ExprError();
1023     break;
1024   case Builtin::BI__builtin_setjmp:
1025     if (SemaBuiltinSetjmp(TheCall))
1026       return ExprError();
1027     break;
1028   case Builtin::BI_setjmp:
1029   case Builtin::BI_setjmpex:
1030     if (checkArgCount(*this, TheCall, 1))
1031       return true;
1032     break;
1033   case Builtin::BI__builtin_classify_type:
1034     if (checkArgCount(*this, TheCall, 1)) return true;
1035     TheCall->setType(Context.IntTy);
1036     break;
1037   case Builtin::BI__builtin_constant_p:
1038     if (checkArgCount(*this, TheCall, 1)) return true;
1039     TheCall->setType(Context.IntTy);
1040     break;
1041   case Builtin::BI__sync_fetch_and_add:
1042   case Builtin::BI__sync_fetch_and_add_1:
1043   case Builtin::BI__sync_fetch_and_add_2:
1044   case Builtin::BI__sync_fetch_and_add_4:
1045   case Builtin::BI__sync_fetch_and_add_8:
1046   case Builtin::BI__sync_fetch_and_add_16:
1047   case Builtin::BI__sync_fetch_and_sub:
1048   case Builtin::BI__sync_fetch_and_sub_1:
1049   case Builtin::BI__sync_fetch_and_sub_2:
1050   case Builtin::BI__sync_fetch_and_sub_4:
1051   case Builtin::BI__sync_fetch_and_sub_8:
1052   case Builtin::BI__sync_fetch_and_sub_16:
1053   case Builtin::BI__sync_fetch_and_or:
1054   case Builtin::BI__sync_fetch_and_or_1:
1055   case Builtin::BI__sync_fetch_and_or_2:
1056   case Builtin::BI__sync_fetch_and_or_4:
1057   case Builtin::BI__sync_fetch_and_or_8:
1058   case Builtin::BI__sync_fetch_and_or_16:
1059   case Builtin::BI__sync_fetch_and_and:
1060   case Builtin::BI__sync_fetch_and_and_1:
1061   case Builtin::BI__sync_fetch_and_and_2:
1062   case Builtin::BI__sync_fetch_and_and_4:
1063   case Builtin::BI__sync_fetch_and_and_8:
1064   case Builtin::BI__sync_fetch_and_and_16:
1065   case Builtin::BI__sync_fetch_and_xor:
1066   case Builtin::BI__sync_fetch_and_xor_1:
1067   case Builtin::BI__sync_fetch_and_xor_2:
1068   case Builtin::BI__sync_fetch_and_xor_4:
1069   case Builtin::BI__sync_fetch_and_xor_8:
1070   case Builtin::BI__sync_fetch_and_xor_16:
1071   case Builtin::BI__sync_fetch_and_nand:
1072   case Builtin::BI__sync_fetch_and_nand_1:
1073   case Builtin::BI__sync_fetch_and_nand_2:
1074   case Builtin::BI__sync_fetch_and_nand_4:
1075   case Builtin::BI__sync_fetch_and_nand_8:
1076   case Builtin::BI__sync_fetch_and_nand_16:
1077   case Builtin::BI__sync_add_and_fetch:
1078   case Builtin::BI__sync_add_and_fetch_1:
1079   case Builtin::BI__sync_add_and_fetch_2:
1080   case Builtin::BI__sync_add_and_fetch_4:
1081   case Builtin::BI__sync_add_and_fetch_8:
1082   case Builtin::BI__sync_add_and_fetch_16:
1083   case Builtin::BI__sync_sub_and_fetch:
1084   case Builtin::BI__sync_sub_and_fetch_1:
1085   case Builtin::BI__sync_sub_and_fetch_2:
1086   case Builtin::BI__sync_sub_and_fetch_4:
1087   case Builtin::BI__sync_sub_and_fetch_8:
1088   case Builtin::BI__sync_sub_and_fetch_16:
1089   case Builtin::BI__sync_and_and_fetch:
1090   case Builtin::BI__sync_and_and_fetch_1:
1091   case Builtin::BI__sync_and_and_fetch_2:
1092   case Builtin::BI__sync_and_and_fetch_4:
1093   case Builtin::BI__sync_and_and_fetch_8:
1094   case Builtin::BI__sync_and_and_fetch_16:
1095   case Builtin::BI__sync_or_and_fetch:
1096   case Builtin::BI__sync_or_and_fetch_1:
1097   case Builtin::BI__sync_or_and_fetch_2:
1098   case Builtin::BI__sync_or_and_fetch_4:
1099   case Builtin::BI__sync_or_and_fetch_8:
1100   case Builtin::BI__sync_or_and_fetch_16:
1101   case Builtin::BI__sync_xor_and_fetch:
1102   case Builtin::BI__sync_xor_and_fetch_1:
1103   case Builtin::BI__sync_xor_and_fetch_2:
1104   case Builtin::BI__sync_xor_and_fetch_4:
1105   case Builtin::BI__sync_xor_and_fetch_8:
1106   case Builtin::BI__sync_xor_and_fetch_16:
1107   case Builtin::BI__sync_nand_and_fetch:
1108   case Builtin::BI__sync_nand_and_fetch_1:
1109   case Builtin::BI__sync_nand_and_fetch_2:
1110   case Builtin::BI__sync_nand_and_fetch_4:
1111   case Builtin::BI__sync_nand_and_fetch_8:
1112   case Builtin::BI__sync_nand_and_fetch_16:
1113   case Builtin::BI__sync_val_compare_and_swap:
1114   case Builtin::BI__sync_val_compare_and_swap_1:
1115   case Builtin::BI__sync_val_compare_and_swap_2:
1116   case Builtin::BI__sync_val_compare_and_swap_4:
1117   case Builtin::BI__sync_val_compare_and_swap_8:
1118   case Builtin::BI__sync_val_compare_and_swap_16:
1119   case Builtin::BI__sync_bool_compare_and_swap:
1120   case Builtin::BI__sync_bool_compare_and_swap_1:
1121   case Builtin::BI__sync_bool_compare_and_swap_2:
1122   case Builtin::BI__sync_bool_compare_and_swap_4:
1123   case Builtin::BI__sync_bool_compare_and_swap_8:
1124   case Builtin::BI__sync_bool_compare_and_swap_16:
1125   case Builtin::BI__sync_lock_test_and_set:
1126   case Builtin::BI__sync_lock_test_and_set_1:
1127   case Builtin::BI__sync_lock_test_and_set_2:
1128   case Builtin::BI__sync_lock_test_and_set_4:
1129   case Builtin::BI__sync_lock_test_and_set_8:
1130   case Builtin::BI__sync_lock_test_and_set_16:
1131   case Builtin::BI__sync_lock_release:
1132   case Builtin::BI__sync_lock_release_1:
1133   case Builtin::BI__sync_lock_release_2:
1134   case Builtin::BI__sync_lock_release_4:
1135   case Builtin::BI__sync_lock_release_8:
1136   case Builtin::BI__sync_lock_release_16:
1137   case Builtin::BI__sync_swap:
1138   case Builtin::BI__sync_swap_1:
1139   case Builtin::BI__sync_swap_2:
1140   case Builtin::BI__sync_swap_4:
1141   case Builtin::BI__sync_swap_8:
1142   case Builtin::BI__sync_swap_16:
1143     return SemaBuiltinAtomicOverloaded(TheCallResult);
1144   case Builtin::BI__sync_synchronize:
1145     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1146         << TheCall->getCallee()->getSourceRange();
1147     break;
1148   case Builtin::BI__builtin_nontemporal_load:
1149   case Builtin::BI__builtin_nontemporal_store:
1150     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1151 #define BUILTIN(ID, TYPE, ATTRS)
1152 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1153   case Builtin::BI##ID: \
1154     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1155 #include "clang/Basic/Builtins.def"
1156   case Builtin::BI__annotation:
1157     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1158       return ExprError();
1159     break;
1160   case Builtin::BI__builtin_annotation:
1161     if (SemaBuiltinAnnotation(*this, TheCall))
1162       return ExprError();
1163     break;
1164   case Builtin::BI__builtin_addressof:
1165     if (SemaBuiltinAddressof(*this, TheCall))
1166       return ExprError();
1167     break;
1168   case Builtin::BI__builtin_add_overflow:
1169   case Builtin::BI__builtin_sub_overflow:
1170   case Builtin::BI__builtin_mul_overflow:
1171     if (SemaBuiltinOverflow(*this, TheCall))
1172       return ExprError();
1173     break;
1174   case Builtin::BI__builtin_operator_new:
1175   case Builtin::BI__builtin_operator_delete: {
1176     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1177     ExprResult Res =
1178         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1179     if (Res.isInvalid())
1180       CorrectDelayedTyposInExpr(TheCallResult.get());
1181     return Res;
1182   }
1183   case Builtin::BI__builtin_dump_struct: {
1184     // We first want to ensure we are called with 2 arguments
1185     if (checkArgCount(*this, TheCall, 2))
1186       return ExprError();
1187     // Ensure that the first argument is of type 'struct XX *'
1188     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1189     const QualType PtrArgType = PtrArg->getType();
1190     if (!PtrArgType->isPointerType() ||
1191         !PtrArgType->getPointeeType()->isRecordType()) {
1192       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1193           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1194           << "structure pointer";
1195       return ExprError();
1196     }
1197 
1198     // Ensure that the second argument is of type 'FunctionType'
1199     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1200     const QualType FnPtrArgType = FnPtrArg->getType();
1201     if (!FnPtrArgType->isPointerType()) {
1202       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1203           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1204           << FnPtrArgType << "'int (*)(const char *, ...)'";
1205       return ExprError();
1206     }
1207 
1208     const auto *FuncType =
1209         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1210 
1211     if (!FuncType) {
1212       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1213           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1214           << FnPtrArgType << "'int (*)(const char *, ...)'";
1215       return ExprError();
1216     }
1217 
1218     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1219       if (!FT->getNumParams()) {
1220         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1221             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1222             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1223         return ExprError();
1224       }
1225       QualType PT = FT->getParamType(0);
1226       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1227           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1228           !PT->getPointeeType().isConstQualified()) {
1229         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1230             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1231             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1232         return ExprError();
1233       }
1234     }
1235 
1236     TheCall->setType(Context.IntTy);
1237     break;
1238   }
1239 
1240   // check secure string manipulation functions where overflows
1241   // are detectable at compile time
1242   case Builtin::BI__builtin___memcpy_chk:
1243     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memcpy");
1244     break;
1245   case Builtin::BI__builtin___memmove_chk:
1246     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memmove");
1247     break;
1248   case Builtin::BI__builtin___memset_chk:
1249     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "memset");
1250     break;
1251   case Builtin::BI__builtin___strlcat_chk:
1252     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcat");
1253     break;
1254   case Builtin::BI__builtin___strlcpy_chk:
1255     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strlcpy");
1256     break;
1257   case Builtin::BI__builtin___strncat_chk:
1258     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncat");
1259     break;
1260   case Builtin::BI__builtin___strncpy_chk:
1261     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "strncpy");
1262     break;
1263   case Builtin::BI__builtin___stpncpy_chk:
1264     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3, "stpncpy");
1265     break;
1266   case Builtin::BI__builtin___memccpy_chk:
1267     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4, "memccpy");
1268     break;
1269   case Builtin::BI__builtin___snprintf_chk:
1270     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "snprintf");
1271     break;
1272   case Builtin::BI__builtin___vsnprintf_chk:
1273     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3, "vsnprintf");
1274     break;
1275   case Builtin::BI__builtin_call_with_static_chain:
1276     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1277       return ExprError();
1278     break;
1279   case Builtin::BI__exception_code:
1280   case Builtin::BI_exception_code:
1281     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1282                                  diag::err_seh___except_block))
1283       return ExprError();
1284     break;
1285   case Builtin::BI__exception_info:
1286   case Builtin::BI_exception_info:
1287     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1288                                  diag::err_seh___except_filter))
1289       return ExprError();
1290     break;
1291   case Builtin::BI__GetExceptionInfo:
1292     if (checkArgCount(*this, TheCall, 1))
1293       return ExprError();
1294 
1295     if (CheckCXXThrowOperand(
1296             TheCall->getBeginLoc(),
1297             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1298             TheCall))
1299       return ExprError();
1300 
1301     TheCall->setType(Context.VoidPtrTy);
1302     break;
1303   // OpenCL v2.0, s6.13.16 - Pipe functions
1304   case Builtin::BIread_pipe:
1305   case Builtin::BIwrite_pipe:
1306     // Since those two functions are declared with var args, we need a semantic
1307     // check for the argument.
1308     if (SemaBuiltinRWPipe(*this, TheCall))
1309       return ExprError();
1310     TheCall->setType(Context.IntTy);
1311     break;
1312   case Builtin::BIreserve_read_pipe:
1313   case Builtin::BIreserve_write_pipe:
1314   case Builtin::BIwork_group_reserve_read_pipe:
1315   case Builtin::BIwork_group_reserve_write_pipe:
1316     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1317       return ExprError();
1318     break;
1319   case Builtin::BIsub_group_reserve_read_pipe:
1320   case Builtin::BIsub_group_reserve_write_pipe:
1321     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1322         SemaBuiltinReserveRWPipe(*this, TheCall))
1323       return ExprError();
1324     break;
1325   case Builtin::BIcommit_read_pipe:
1326   case Builtin::BIcommit_write_pipe:
1327   case Builtin::BIwork_group_commit_read_pipe:
1328   case Builtin::BIwork_group_commit_write_pipe:
1329     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1330       return ExprError();
1331     break;
1332   case Builtin::BIsub_group_commit_read_pipe:
1333   case Builtin::BIsub_group_commit_write_pipe:
1334     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1335         SemaBuiltinCommitRWPipe(*this, TheCall))
1336       return ExprError();
1337     break;
1338   case Builtin::BIget_pipe_num_packets:
1339   case Builtin::BIget_pipe_max_packets:
1340     if (SemaBuiltinPipePackets(*this, TheCall))
1341       return ExprError();
1342     TheCall->setType(Context.UnsignedIntTy);
1343     break;
1344   case Builtin::BIto_global:
1345   case Builtin::BIto_local:
1346   case Builtin::BIto_private:
1347     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1348       return ExprError();
1349     break;
1350   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1351   case Builtin::BIenqueue_kernel:
1352     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1353       return ExprError();
1354     break;
1355   case Builtin::BIget_kernel_work_group_size:
1356   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1357     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1358       return ExprError();
1359     break;
1360   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1361   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1362     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1363       return ExprError();
1364     break;
1365   case Builtin::BI__builtin_os_log_format:
1366   case Builtin::BI__builtin_os_log_format_buffer_size:
1367     if (SemaBuiltinOSLogFormat(TheCall))
1368       return ExprError();
1369     break;
1370   }
1371 
1372   // Since the target specific builtins for each arch overlap, only check those
1373   // of the arch we are compiling for.
1374   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1375     switch (Context.getTargetInfo().getTriple().getArch()) {
1376       case llvm::Triple::arm:
1377       case llvm::Triple::armeb:
1378       case llvm::Triple::thumb:
1379       case llvm::Triple::thumbeb:
1380         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1381           return ExprError();
1382         break;
1383       case llvm::Triple::aarch64:
1384       case llvm::Triple::aarch64_be:
1385         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1386           return ExprError();
1387         break;
1388       case llvm::Triple::hexagon:
1389         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1390           return ExprError();
1391         break;
1392       case llvm::Triple::mips:
1393       case llvm::Triple::mipsel:
1394       case llvm::Triple::mips64:
1395       case llvm::Triple::mips64el:
1396         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1397           return ExprError();
1398         break;
1399       case llvm::Triple::systemz:
1400         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1401           return ExprError();
1402         break;
1403       case llvm::Triple::x86:
1404       case llvm::Triple::x86_64:
1405         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1406           return ExprError();
1407         break;
1408       case llvm::Triple::ppc:
1409       case llvm::Triple::ppc64:
1410       case llvm::Triple::ppc64le:
1411         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1412           return ExprError();
1413         break;
1414       default:
1415         break;
1416     }
1417   }
1418 
1419   return TheCallResult;
1420 }
1421 
1422 // Get the valid immediate range for the specified NEON type code.
1423 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1424   NeonTypeFlags Type(t);
1425   int IsQuad = ForceQuad ? true : Type.isQuad();
1426   switch (Type.getEltType()) {
1427   case NeonTypeFlags::Int8:
1428   case NeonTypeFlags::Poly8:
1429     return shift ? 7 : (8 << IsQuad) - 1;
1430   case NeonTypeFlags::Int16:
1431   case NeonTypeFlags::Poly16:
1432     return shift ? 15 : (4 << IsQuad) - 1;
1433   case NeonTypeFlags::Int32:
1434     return shift ? 31 : (2 << IsQuad) - 1;
1435   case NeonTypeFlags::Int64:
1436   case NeonTypeFlags::Poly64:
1437     return shift ? 63 : (1 << IsQuad) - 1;
1438   case NeonTypeFlags::Poly128:
1439     return shift ? 127 : (1 << IsQuad) - 1;
1440   case NeonTypeFlags::Float16:
1441     assert(!shift && "cannot shift float types!");
1442     return (4 << IsQuad) - 1;
1443   case NeonTypeFlags::Float32:
1444     assert(!shift && "cannot shift float types!");
1445     return (2 << IsQuad) - 1;
1446   case NeonTypeFlags::Float64:
1447     assert(!shift && "cannot shift float types!");
1448     return (1 << IsQuad) - 1;
1449   }
1450   llvm_unreachable("Invalid NeonTypeFlag!");
1451 }
1452 
1453 /// getNeonEltType - Return the QualType corresponding to the elements of
1454 /// the vector type specified by the NeonTypeFlags.  This is used to check
1455 /// the pointer arguments for Neon load/store intrinsics.
1456 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1457                                bool IsPolyUnsigned, bool IsInt64Long) {
1458   switch (Flags.getEltType()) {
1459   case NeonTypeFlags::Int8:
1460     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1461   case NeonTypeFlags::Int16:
1462     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1463   case NeonTypeFlags::Int32:
1464     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1465   case NeonTypeFlags::Int64:
1466     if (IsInt64Long)
1467       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1468     else
1469       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1470                                 : Context.LongLongTy;
1471   case NeonTypeFlags::Poly8:
1472     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1473   case NeonTypeFlags::Poly16:
1474     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1475   case NeonTypeFlags::Poly64:
1476     if (IsInt64Long)
1477       return Context.UnsignedLongTy;
1478     else
1479       return Context.UnsignedLongLongTy;
1480   case NeonTypeFlags::Poly128:
1481     break;
1482   case NeonTypeFlags::Float16:
1483     return Context.HalfTy;
1484   case NeonTypeFlags::Float32:
1485     return Context.FloatTy;
1486   case NeonTypeFlags::Float64:
1487     return Context.DoubleTy;
1488   }
1489   llvm_unreachable("Invalid NeonTypeFlag!");
1490 }
1491 
1492 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1493   llvm::APSInt Result;
1494   uint64_t mask = 0;
1495   unsigned TV = 0;
1496   int PtrArgNum = -1;
1497   bool HasConstPtr = false;
1498   switch (BuiltinID) {
1499 #define GET_NEON_OVERLOAD_CHECK
1500 #include "clang/Basic/arm_neon.inc"
1501 #include "clang/Basic/arm_fp16.inc"
1502 #undef GET_NEON_OVERLOAD_CHECK
1503   }
1504 
1505   // For NEON intrinsics which are overloaded on vector element type, validate
1506   // the immediate which specifies which variant to emit.
1507   unsigned ImmArg = TheCall->getNumArgs()-1;
1508   if (mask) {
1509     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1510       return true;
1511 
1512     TV = Result.getLimitedValue(64);
1513     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1514       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1515              << TheCall->getArg(ImmArg)->getSourceRange();
1516   }
1517 
1518   if (PtrArgNum >= 0) {
1519     // Check that pointer arguments have the specified type.
1520     Expr *Arg = TheCall->getArg(PtrArgNum);
1521     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1522       Arg = ICE->getSubExpr();
1523     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1524     QualType RHSTy = RHS.get()->getType();
1525 
1526     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1527     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1528                           Arch == llvm::Triple::aarch64_be;
1529     bool IsInt64Long =
1530         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1531     QualType EltTy =
1532         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1533     if (HasConstPtr)
1534       EltTy = EltTy.withConst();
1535     QualType LHSTy = Context.getPointerType(EltTy);
1536     AssignConvertType ConvTy;
1537     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1538     if (RHS.isInvalid())
1539       return true;
1540     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1541                                  RHS.get(), AA_Assigning))
1542       return true;
1543   }
1544 
1545   // For NEON intrinsics which take an immediate value as part of the
1546   // instruction, range check them here.
1547   unsigned i = 0, l = 0, u = 0;
1548   switch (BuiltinID) {
1549   default:
1550     return false;
1551   #define GET_NEON_IMMEDIATE_CHECK
1552   #include "clang/Basic/arm_neon.inc"
1553   #include "clang/Basic/arm_fp16.inc"
1554   #undef GET_NEON_IMMEDIATE_CHECK
1555   }
1556 
1557   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1558 }
1559 
1560 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1561                                         unsigned MaxWidth) {
1562   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1563           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1564           BuiltinID == ARM::BI__builtin_arm_strex ||
1565           BuiltinID == ARM::BI__builtin_arm_stlex ||
1566           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1567           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1568           BuiltinID == AArch64::BI__builtin_arm_strex ||
1569           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1570          "unexpected ARM builtin");
1571   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1572                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1573                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1574                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1575 
1576   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1577 
1578   // Ensure that we have the proper number of arguments.
1579   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1580     return true;
1581 
1582   // Inspect the pointer argument of the atomic builtin.  This should always be
1583   // a pointer type, whose element is an integral scalar or pointer type.
1584   // Because it is a pointer type, we don't have to worry about any implicit
1585   // casts here.
1586   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1587   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1588   if (PointerArgRes.isInvalid())
1589     return true;
1590   PointerArg = PointerArgRes.get();
1591 
1592   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1593   if (!pointerType) {
1594     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1595         << PointerArg->getType() << PointerArg->getSourceRange();
1596     return true;
1597   }
1598 
1599   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1600   // task is to insert the appropriate casts into the AST. First work out just
1601   // what the appropriate type is.
1602   QualType ValType = pointerType->getPointeeType();
1603   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1604   if (IsLdrex)
1605     AddrType.addConst();
1606 
1607   // Issue a warning if the cast is dodgy.
1608   CastKind CastNeeded = CK_NoOp;
1609   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1610     CastNeeded = CK_BitCast;
1611     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1612         << PointerArg->getType() << Context.getPointerType(AddrType)
1613         << AA_Passing << PointerArg->getSourceRange();
1614   }
1615 
1616   // Finally, do the cast and replace the argument with the corrected version.
1617   AddrType = Context.getPointerType(AddrType);
1618   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1619   if (PointerArgRes.isInvalid())
1620     return true;
1621   PointerArg = PointerArgRes.get();
1622 
1623   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1624 
1625   // In general, we allow ints, floats and pointers to be loaded and stored.
1626   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1627       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1628     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1629         << PointerArg->getType() << PointerArg->getSourceRange();
1630     return true;
1631   }
1632 
1633   // But ARM doesn't have instructions to deal with 128-bit versions.
1634   if (Context.getTypeSize(ValType) > MaxWidth) {
1635     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1636     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1637         << PointerArg->getType() << PointerArg->getSourceRange();
1638     return true;
1639   }
1640 
1641   switch (ValType.getObjCLifetime()) {
1642   case Qualifiers::OCL_None:
1643   case Qualifiers::OCL_ExplicitNone:
1644     // okay
1645     break;
1646 
1647   case Qualifiers::OCL_Weak:
1648   case Qualifiers::OCL_Strong:
1649   case Qualifiers::OCL_Autoreleasing:
1650     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1651         << ValType << PointerArg->getSourceRange();
1652     return true;
1653   }
1654 
1655   if (IsLdrex) {
1656     TheCall->setType(ValType);
1657     return false;
1658   }
1659 
1660   // Initialize the argument to be stored.
1661   ExprResult ValArg = TheCall->getArg(0);
1662   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1663       Context, ValType, /*consume*/ false);
1664   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1665   if (ValArg.isInvalid())
1666     return true;
1667   TheCall->setArg(0, ValArg.get());
1668 
1669   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1670   // but the custom checker bypasses all default analysis.
1671   TheCall->setType(Context.IntTy);
1672   return false;
1673 }
1674 
1675 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1676   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1677       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1678       BuiltinID == ARM::BI__builtin_arm_strex ||
1679       BuiltinID == ARM::BI__builtin_arm_stlex) {
1680     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1681   }
1682 
1683   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1684     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1685       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1686   }
1687 
1688   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1689       BuiltinID == ARM::BI__builtin_arm_wsr64)
1690     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1691 
1692   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1693       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1694       BuiltinID == ARM::BI__builtin_arm_wsr ||
1695       BuiltinID == ARM::BI__builtin_arm_wsrp)
1696     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1697 
1698   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1699     return true;
1700 
1701   // For intrinsics which take an immediate value as part of the instruction,
1702   // range check them here.
1703   // FIXME: VFP Intrinsics should error if VFP not present.
1704   switch (BuiltinID) {
1705   default: return false;
1706   case ARM::BI__builtin_arm_ssat:
1707     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1708   case ARM::BI__builtin_arm_usat:
1709     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1710   case ARM::BI__builtin_arm_ssat16:
1711     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1712   case ARM::BI__builtin_arm_usat16:
1713     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1714   case ARM::BI__builtin_arm_vcvtr_f:
1715   case ARM::BI__builtin_arm_vcvtr_d:
1716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1717   case ARM::BI__builtin_arm_dmb:
1718   case ARM::BI__builtin_arm_dsb:
1719   case ARM::BI__builtin_arm_isb:
1720   case ARM::BI__builtin_arm_dbg:
1721     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1722   }
1723 }
1724 
1725 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1726                                          CallExpr *TheCall) {
1727   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1728       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1729       BuiltinID == AArch64::BI__builtin_arm_strex ||
1730       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1731     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1732   }
1733 
1734   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1735     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1736       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1737       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1738       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1739   }
1740 
1741   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1742       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1743     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1744 
1745   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1746       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1747       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1748       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1749     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1750 
1751   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1752     return true;
1753 
1754   // For intrinsics which take an immediate value as part of the instruction,
1755   // range check them here.
1756   unsigned i = 0, l = 0, u = 0;
1757   switch (BuiltinID) {
1758   default: return false;
1759   case AArch64::BI__builtin_arm_dmb:
1760   case AArch64::BI__builtin_arm_dsb:
1761   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1762   }
1763 
1764   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1765 }
1766 
1767 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1768   static const std::map<unsigned, std::vector<StringRef>> ValidCPU = {
1769     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, {"v65"} },
1770     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, {"v62", "v65"} },
1771     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, {"v62", "v65"} },
1772     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, {"v62", "v65"} },
1773     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {"v60", "v62", "v65"} },
1774     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {"v60", "v62", "v65"} },
1775     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {"v60", "v62", "v65"} },
1776     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {"v60", "v62", "v65"} },
1777     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {"v60", "v62", "v65"} },
1778     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {"v60", "v62", "v65"} },
1779     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {"v60", "v62", "v65"} },
1780     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {"v60", "v62", "v65"} },
1781     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {"v60", "v62", "v65"} },
1782     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {"v60", "v62", "v65"} },
1783     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {"v60", "v62", "v65"} },
1784     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {"v60", "v62", "v65"} },
1785     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, {"v62", "v65"} },
1786     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, {"v62", "v65"} },
1787     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, {"v62", "v65"} },
1788   };
1789 
1790   static const std::map<unsigned, std::vector<StringRef>> ValidHVX = {
1791     { Hexagon::BI__builtin_HEXAGON_V6_extractw, {"v60", "v62", "v65"} },
1792     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, {"v60", "v62", "v65"} },
1793     { Hexagon::BI__builtin_HEXAGON_V6_hi, {"v60", "v62", "v65"} },
1794     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, {"v60", "v62", "v65"} },
1795     { Hexagon::BI__builtin_HEXAGON_V6_lo, {"v60", "v62", "v65"} },
1796     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, {"v60", "v62", "v65"} },
1797     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, {"v62", "v65"} },
1798     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, {"v62", "v65"} },
1799     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, {"v62", "v65"} },
1800     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, {"v62", "v65"} },
1801     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, {"v60", "v62", "v65"} },
1802     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, {"v60", "v62", "v65"} },
1803     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, {"v60", "v62", "v65"} },
1804     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, {"v60", "v62", "v65"} },
1805     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, {"v60", "v62", "v65"} },
1806     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, {"v60", "v62", "v65"} },
1807     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, {"v60", "v62", "v65"} },
1808     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, {"v60", "v62", "v65"} },
1809     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, {"v60", "v62", "v65"} },
1810     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, {"v60", "v62", "v65"} },
1811     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, {"v60", "v62", "v65"} },
1812     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, {"v60", "v62", "v65"} },
1813     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, {"v60", "v62", "v65"} },
1814     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, {"v60", "v62", "v65"} },
1815     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, {"v62", "v65"} },
1816     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, {"v62", "v65"} },
1817     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, {"v60", "v62", "v65"} },
1818     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, {"v60", "v62", "v65"} },
1819     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, {"v62", "v65"} },
1820     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, {"v62", "v65"} },
1821     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, {"v62", "v65"} },
1822     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, {"v62", "v65"} },
1823     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, {"v65"} },
1824     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, {"v65"} },
1825     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, {"v65"} },
1826     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, {"v65"} },
1827     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, {"v60", "v62", "v65"} },
1828     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, {"v60", "v62", "v65"} },
1829     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, {"v60", "v62", "v65"} },
1830     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, {"v60", "v62", "v65"} },
1831     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, {"v60", "v62", "v65"} },
1832     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, {"v60", "v62", "v65"} },
1833     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, {"v60", "v62", "v65"} },
1834     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, {"v60", "v62", "v65"} },
1835     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, {"v60", "v62", "v65"} },
1836     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, {"v60", "v62", "v65"} },
1837     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, {"v60", "v62", "v65"} },
1838     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, {"v60", "v62", "v65"} },
1839     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, {"v60", "v62", "v65"} },
1840     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, {"v60", "v62", "v65"} },
1841     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, {"v60", "v62", "v65"} },
1842     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, {"v60", "v62", "v65"} },
1843     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, {"v60", "v62", "v65"} },
1844     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, {"v60", "v62", "v65"} },
1845     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, {"v60", "v62", "v65"} },
1846     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, {"v60", "v62", "v65"} },
1847     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, {"v62", "v65"} },
1848     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, {"v62", "v65"} },
1849     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, {"v62", "v65"} },
1850     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, {"v62", "v65"} },
1851     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, {"v62", "v65"} },
1852     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, {"v62", "v65"} },
1853     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, {"v62", "v65"} },
1854     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, {"v62", "v65"} },
1855     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, {"v62", "v65"} },
1856     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, {"v62", "v65"} },
1857     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, {"v60", "v62", "v65"} },
1858     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, {"v60", "v62", "v65"} },
1859     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, {"v60", "v62", "v65"} },
1860     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, {"v60", "v62", "v65"} },
1861     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, {"v60", "v62", "v65"} },
1862     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, {"v60", "v62", "v65"} },
1863     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, {"v60", "v62", "v65"} },
1864     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, {"v60", "v62", "v65"} },
1865     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, {"v60", "v62", "v65"} },
1866     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, {"v60", "v62", "v65"} },
1867     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, {"v62", "v65"} },
1868     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, {"v62", "v65"} },
1869     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, {"v60", "v62", "v65"} },
1870     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, {"v60", "v62", "v65"} },
1871     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, {"v62", "v65"} },
1872     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, {"v62", "v65"} },
1873     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, {"v60", "v62", "v65"} },
1874     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, {"v60", "v62", "v65"} },
1875     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, {"v60", "v62", "v65"} },
1876     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, {"v60", "v62", "v65"} },
1877     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, {"v62", "v65"} },
1878     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, {"v62", "v65"} },
1879     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, {"v60", "v62", "v65"} },
1880     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, {"v60", "v62", "v65"} },
1881     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, {"v60", "v62", "v65"} },
1882     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, {"v60", "v62", "v65"} },
1883     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, {"v60", "v62", "v65"} },
1884     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, {"v60", "v62", "v65"} },
1885     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, {"v62", "v65"} },
1886     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, {"v62", "v65"} },
1887     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, {"v62", "v65"} },
1888     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, {"v62", "v65"} },
1889     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, {"v62", "v65"} },
1890     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, {"v62", "v65"} },
1891     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, {"v60", "v62", "v65"} },
1892     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, {"v60", "v62", "v65"} },
1893     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, {"v60", "v62", "v65"} },
1894     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, {"v60", "v62", "v65"} },
1895     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, {"v60", "v62", "v65"} },
1896     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, {"v60", "v62", "v65"} },
1897     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, {"v60", "v62", "v65"} },
1898     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, {"v60", "v62", "v65"} },
1899     { Hexagon::BI__builtin_HEXAGON_V6_valignb, {"v60", "v62", "v65"} },
1900     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, {"v60", "v62", "v65"} },
1901     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {"v60", "v62", "v65"} },
1902     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {"v60", "v62", "v65"} },
1903     { Hexagon::BI__builtin_HEXAGON_V6_vand, {"v60", "v62", "v65"} },
1904     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, {"v60", "v62", "v65"} },
1905     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, {"v62", "v65"} },
1906     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, {"v62", "v65"} },
1907     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, {"v62", "v65"} },
1908     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, {"v62", "v65"} },
1909     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, {"v60", "v62", "v65"} },
1910     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, {"v60", "v62", "v65"} },
1911     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, {"v60", "v62", "v65"} },
1912     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, {"v60", "v62", "v65"} },
1913     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, {"v62", "v65"} },
1914     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, {"v62", "v65"} },
1915     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, {"v62", "v65"} },
1916     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, {"v62", "v65"} },
1917     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, {"v60", "v62", "v65"} },
1918     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, {"v60", "v62", "v65"} },
1919     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, {"v60", "v62", "v65"} },
1920     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, {"v60", "v62", "v65"} },
1921     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, {"v60", "v62", "v65"} },
1922     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, {"v60", "v62", "v65"} },
1923     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, {"v65"} },
1924     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, {"v65"} },
1925     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, {"v60", "v62", "v65"} },
1926     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, {"v60", "v62", "v65"} },
1927     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, {"v60", "v62", "v65"} },
1928     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, {"v60", "v62", "v65"} },
1929     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, {"v60", "v62", "v65"} },
1930     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, {"v60", "v62", "v65"} },
1931     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, {"v60", "v62", "v65"} },
1932     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, {"v60", "v62", "v65"} },
1933     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, {"v60", "v62", "v65"} },
1934     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, {"v60", "v62", "v65"} },
1935     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, {"v65"} },
1936     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, {"v65"} },
1937     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, {"v60", "v62", "v65"} },
1938     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, {"v60", "v62", "v65"} },
1939     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, {"v62", "v65"} },
1940     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, {"v62", "v65"} },
1941     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, {"v60", "v62", "v65"} },
1942     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, {"v60", "v62", "v65"} },
1943     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, {"v60", "v62", "v65"} },
1944     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, {"v60", "v62", "v65"} },
1945     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, {"v60", "v62", "v65"} },
1946     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, {"v60", "v62", "v65"} },
1947     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, {"v65"} },
1948     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, {"v65"} },
1949     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, {"v65"} },
1950     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, {"v65"} },
1951     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, {"v62", "v65"} },
1952     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, {"v62", "v65"} },
1953     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, {"v65"} },
1954     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, {"v65"} },
1955     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, {"v60", "v62", "v65"} },
1956     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, {"v60", "v62", "v65"} },
1957     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, {"v60", "v62", "v65"} },
1958     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, {"v60", "v62", "v65"} },
1959     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, {"v60", "v62", "v65"} },
1960     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, {"v60", "v62", "v65"} },
1961     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, {"v60", "v62", "v65"} },
1962     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, {"v60", "v62", "v65"} },
1963     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, {"v60", "v62", "v65"} },
1964     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, {"v60", "v62", "v65"} },
1965     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, {"v62", "v65"} },
1966     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, {"v62", "v65"} },
1967     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, {"v60", "v62", "v65"} },
1968     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, {"v60", "v62", "v65"} },
1969     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, {"v60", "v62", "v65"} },
1970     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, {"v60", "v62", "v65"} },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vassign, {"v60", "v62", "v65"} },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, {"v60", "v62", "v65"} },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, {"v60", "v62", "v65"} },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, {"v60", "v62", "v65"} },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, {"v65"} },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, {"v65"} },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, {"v65"} },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, {"v65"} },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, {"v60", "v62", "v65"} },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, {"v60", "v62", "v65"} },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, {"v60", "v62", "v65"} },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, {"v60", "v62", "v65"} },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, {"v60", "v62", "v65"} },
1984     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, {"v60", "v62", "v65"} },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, {"v60", "v62", "v65"} },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, {"v60", "v62", "v65"} },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, {"v60", "v62", "v65"} },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, {"v60", "v62", "v65"} },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, {"v60", "v62", "v65"} },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, {"v60", "v62", "v65"} },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, {"v65"} },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, {"v65"} },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, {"v65"} },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, {"v65"} },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, {"v60", "v62", "v65"} },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, {"v60", "v62", "v65"} },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, {"v60", "v62", "v65"} },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, {"v60", "v62", "v65"} },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, {"v60", "v62", "v65"} },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, {"v60", "v62", "v65"} },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, {"v60", "v62", "v65"} },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, {"v60", "v62", "v65"} },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, {"v60", "v62", "v65"} },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, {"v60", "v62", "v65"} },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vd0, {"v60", "v62", "v65"} },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, {"v60", "v62", "v65"} },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, {"v65"} },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, {"v65"} },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, {"v60", "v62", "v65"} },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, {"v60", "v62", "v65"} },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, {"v60", "v62", "v65"} },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, {"v60", "v62", "v65"} },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, {"v60", "v62", "v65"} },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, {"v60", "v62", "v65"} },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, {"v60", "v62", "v65"} },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, {"v60", "v62", "v65"} },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, {"v60", "v62", "v65"} },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, {"v60", "v62", "v65"} },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, {"v60", "v62", "v65"} },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, {"v60", "v62", "v65"} },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, {"v60", "v62", "v65"} },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, {"v60", "v62", "v65"} },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, {"v60", "v62", "v65"} },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, {"v60", "v62", "v65"} },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, {"v60", "v62", "v65"} },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, {"v60", "v62", "v65"} },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, {"v60", "v62", "v65"} },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, {"v60", "v62", "v65"} },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, {"v60", "v62", "v65"} },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, {"v60", "v62", "v65"} },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, {"v60", "v62", "v65"} },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, {"v60", "v62", "v65"} },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, {"v60", "v62", "v65"} },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, {"v60", "v62", "v65"} },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, {"v60", "v62", "v65"} },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, {"v60", "v62", "v65"} },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, {"v60", "v62", "v65"} },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, {"v60", "v62", "v65"} },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, {"v60", "v62", "v65"} },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, {"v60", "v62", "v65"} },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, {"v60", "v62", "v65"} },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, {"v60", "v62", "v65"} },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, {"v60", "v62", "v65"} },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, {"v60", "v62", "v65"} },
2045     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, {"v60", "v62", "v65"} },
2046     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, {"v60", "v62", "v65"} },
2047     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, {"v60", "v62", "v65"} },
2048     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, {"v60", "v62", "v65"} },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, {"v60", "v62", "v65"} },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, {"v60", "v62", "v65"} },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, {"v60", "v62", "v65"} },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, {"v60", "v62", "v65"} },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, {"v60", "v62", "v65"} },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, {"v60", "v62", "v65"} },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, {"v60", "v62", "v65"} },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, {"v60", "v62", "v65"} },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, {"v60", "v62", "v65"} },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, {"v60", "v62", "v65"} },
2059     { Hexagon::BI__builtin_HEXAGON_V6_veqb, {"v60", "v62", "v65"} },
2060     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, {"v60", "v62", "v65"} },
2061     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, {"v60", "v62", "v65"} },
2062     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, {"v60", "v62", "v65"} },
2063     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, {"v60", "v62", "v65"} },
2064     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, {"v60", "v62", "v65"} },
2065     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, {"v60", "v62", "v65"} },
2066     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, {"v60", "v62", "v65"} },
2067     { Hexagon::BI__builtin_HEXAGON_V6_veqh, {"v60", "v62", "v65"} },
2068     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, {"v60", "v62", "v65"} },
2069     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, {"v60", "v62", "v65"} },
2070     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, {"v60", "v62", "v65"} },
2071     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, {"v60", "v62", "v65"} },
2072     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, {"v60", "v62", "v65"} },
2073     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, {"v60", "v62", "v65"} },
2074     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, {"v60", "v62", "v65"} },
2075     { Hexagon::BI__builtin_HEXAGON_V6_veqw, {"v60", "v62", "v65"} },
2076     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, {"v60", "v62", "v65"} },
2077     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, {"v60", "v62", "v65"} },
2078     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, {"v60", "v62", "v65"} },
2079     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, {"v60", "v62", "v65"} },
2080     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, {"v60", "v62", "v65"} },
2081     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, {"v60", "v62", "v65"} },
2082     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, {"v60", "v62", "v65"} },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, {"v60", "v62", "v65"} },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, {"v60", "v62", "v65"} },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, {"v60", "v62", "v65"} },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, {"v60", "v62", "v65"} },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, {"v60", "v62", "v65"} },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, {"v60", "v62", "v65"} },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, {"v60", "v62", "v65"} },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, {"v60", "v62", "v65"} },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vgth, {"v60", "v62", "v65"} },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, {"v60", "v62", "v65"} },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, {"v60", "v62", "v65"} },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, {"v60", "v62", "v65"} },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, {"v60", "v62", "v65"} },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, {"v60", "v62", "v65"} },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, {"v60", "v62", "v65"} },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, {"v60", "v62", "v65"} },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, {"v60", "v62", "v65"} },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, {"v60", "v62", "v65"} },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, {"v60", "v62", "v65"} },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, {"v60", "v62", "v65"} },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, {"v60", "v62", "v65"} },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, {"v60", "v62", "v65"} },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, {"v60", "v62", "v65"} },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, {"v60", "v62", "v65"} },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, {"v60", "v62", "v65"} },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, {"v60", "v62", "v65"} },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, {"v60", "v62", "v65"} },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, {"v60", "v62", "v65"} },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, {"v60", "v62", "v65"} },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, {"v60", "v62", "v65"} },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, {"v60", "v62", "v65"} },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, {"v60", "v62", "v65"} },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, {"v60", "v62", "v65"} },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, {"v60", "v62", "v65"} },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, {"v60", "v62", "v65"} },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, {"v60", "v62", "v65"} },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, {"v60", "v62", "v65"} },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, {"v60", "v62", "v65"} },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, {"v60", "v62", "v65"} },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, {"v60", "v62", "v65"} },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, {"v60", "v62", "v65"} },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, {"v60", "v62", "v65"} },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, {"v60", "v62", "v65"} },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, {"v60", "v62", "v65"} },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, {"v60", "v62", "v65"} },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, {"v60", "v62", "v65"} },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, {"v60", "v62", "v65"} },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, {"v60", "v62", "v65"} },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, {"v60", "v62", "v65"} },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, {"v60", "v62", "v65"} },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, {"v60", "v62", "v65"} },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, {"v60", "v62", "v65"} },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {"v60", "v62", "v65"} },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {"v60", "v62", "v65"} },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, {"v62", "v65"} },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, {"v62", "v65"} },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, {"v60", "v62", "v65"} },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, {"v60", "v62", "v65"} },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, {"v60", "v62", "v65"} },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, {"v60", "v62", "v65"} },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, {"v60", "v62", "v65"} },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, {"v60", "v62", "v65"} },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, {"v60", "v62", "v65"} },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, {"v60", "v62", "v65"} },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, {"v65"} },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, {"v65"} },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, {"v60", "v62", "v65"} },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, {"v60", "v62", "v65"} },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, {"v62", "v65"} },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, {"v62", "v65"} },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, {"v62", "v65"} },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, {"v62", "v65"} },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, {"v60", "v62", "v65"} },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, {"v60", "v62", "v65"} },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, {"v62", "v65"} },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, {"v62", "v65"} },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, {"v60", "v62", "v65"} },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, {"v60", "v62", "v65"} },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, {"v62", "v65"} },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, {"v62", "v65"} },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, {"v62", "v65"} },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, {"v62", "v65"} },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, {"v60", "v62", "v65"} },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, {"v60", "v62", "v65"} },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, {"v62", "v65"} },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, {"v62", "v65"} },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, {"v62", "v65"} },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, {"v62", "v65"} },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, {"v60", "v62", "v65"} },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, {"v60", "v62", "v65"} },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, {"v60", "v62", "v65"} },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, {"v60", "v62", "v65"} },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, {"v60", "v62", "v65"} },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, {"v60", "v62", "v65"} },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, {"v60", "v62", "v65"} },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, {"v60", "v62", "v65"} },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vminb, {"v62", "v65"} },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, {"v62", "v65"} },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vminh, {"v60", "v62", "v65"} },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, {"v60", "v62", "v65"} },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vminub, {"v60", "v62", "v65"} },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, {"v60", "v62", "v65"} },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, {"v60", "v62", "v65"} },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, {"v60", "v62", "v65"} },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vminw, {"v60", "v62", "v65"} },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, {"v60", "v62", "v65"} },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, {"v60", "v62", "v65"} },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, {"v60", "v62", "v65"} },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, {"v60", "v62", "v65"} },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, {"v60", "v62", "v65"} },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, {"v60", "v62", "v65"} },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, {"v60", "v62", "v65"} },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, {"v65"} },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, {"v65"} },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, {"v65"} },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, {"v65"} },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, {"v60", "v62", "v65"} },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, {"v60", "v62", "v65"} },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, {"v60", "v62", "v65"} },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, {"v60", "v62", "v65"} },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, {"v60", "v62", "v65"} },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, {"v60", "v62", "v65"} },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, {"v65"} },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, {"v65"} },
2207     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, {"v62", "v65"} },
2208     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, {"v62", "v65"} },
2209     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, {"v62", "v65"} },
2210     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, {"v62", "v65"} },
2211     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, {"v65"} },
2212     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, {"v65"} },
2213     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, {"v65"} },
2214     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, {"v65"} },
2215     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, {"v60", "v62", "v65"} },
2216     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, {"v60", "v62", "v65"} },
2217     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, {"v60", "v62", "v65"} },
2218     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, {"v60", "v62", "v65"} },
2219     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, {"v60", "v62", "v65"} },
2220     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, {"v60", "v62", "v65"} },
2221     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, {"v60", "v62", "v65"} },
2222     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, {"v60", "v62", "v65"} },
2223     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, {"v60", "v62", "v65"} },
2224     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, {"v60", "v62", "v65"} },
2225     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, {"v60", "v62", "v65"} },
2226     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, {"v60", "v62", "v65"} },
2227     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, {"v60", "v62", "v65"} },
2228     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, {"v60", "v62", "v65"} },
2229     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, {"v62", "v65"} },
2230     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, {"v62", "v65"} },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, {"v60", "v62", "v65"} },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, {"v60", "v62", "v65"} },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, {"v65"} },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, {"v65"} },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, {"v60", "v62", "v65"} },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, {"v60", "v62", "v65"} },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, {"v60", "v62", "v65"} },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, {"v60", "v62", "v65"} },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, {"v60", "v62", "v65"} },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, {"v60", "v62", "v65"} },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, {"v60", "v62", "v65"} },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, {"v60", "v62", "v65"} },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, {"v60", "v62", "v65"} },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, {"v60", "v62", "v65"} },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, {"v60", "v62", "v65"} },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, {"v60", "v62", "v65"} },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, {"v60", "v62", "v65"} },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, {"v60", "v62", "v65"} },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, {"v60", "v62", "v65"} },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, {"v60", "v62", "v65"} },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, {"v60", "v62", "v65"} },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, {"v60", "v62", "v65"} },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, {"v60", "v62", "v65"} },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, {"v60", "v62", "v65"} },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, {"v60", "v62", "v65"} },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, {"v60", "v62", "v65"} },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, {"v60", "v62", "v65"} },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, {"v60", "v62", "v65"} },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, {"v60", "v62", "v65"} },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, {"v60", "v62", "v65"} },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, {"v60", "v62", "v65"} },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, {"v60", "v62", "v65"} },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, {"v60", "v62", "v65"} },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, {"v60", "v62", "v65"} },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, {"v60", "v62", "v65"} },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, {"v60", "v62", "v65"} },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, {"v60", "v62", "v65"} },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, {"v60", "v62", "v65"} },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, {"v60", "v62", "v65"} },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, {"v60", "v62", "v65"} },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, {"v60", "v62", "v65"} },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, {"v60", "v62", "v65"} },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, {"v60", "v62", "v65"} },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, {"v60", "v62", "v65"} },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, {"v60", "v62", "v65"} },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, {"v60", "v62", "v65"} },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, {"v62", "v65"} },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, {"v62", "v65"} },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, {"v62", "v65"} },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, {"v62", "v65"} },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, {"v60", "v62", "v65"} },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, {"v60", "v62", "v65"} },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, {"v62", "v65"} },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, {"v62", "v65"} },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, {"v60", "v62", "v65"} },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, {"v60", "v62", "v65"} },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, {"v60", "v62", "v65"} },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, {"v60", "v62", "v65"} },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, {"v60", "v62", "v65"} },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, {"v60", "v62", "v65"} },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, {"v60", "v62", "v65"} },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, {"v60", "v62", "v65"} },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, {"v60", "v62", "v65"} },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, {"v60", "v62", "v65"} },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, {"v60", "v62", "v65"} },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, {"v60", "v62", "v65"} },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, {"v60", "v62", "v65"} },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, {"v60", "v62", "v65"} },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, {"v60", "v62", "v65"} },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, {"v60", "v62", "v65"} },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, {"v60", "v62", "v65"} },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, {"v60", "v62", "v65"} },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, {"v65"} },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, {"v65"} },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, {"v65"} },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, {"v65"} },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, {"v60", "v62", "v65"} },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, {"v60", "v62", "v65"} },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, {"v60", "v62", "v65"} },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, {"v60", "v62", "v65"} },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vmux, {"v60", "v62", "v65"} },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, {"v60", "v62", "v65"} },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, {"v65"} },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, {"v65"} },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, {"v60", "v62", "v65"} },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, {"v60", "v62", "v65"} },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, {"v60", "v62", "v65"} },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, {"v60", "v62", "v65"} },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, {"v60", "v62", "v65"} },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, {"v60", "v62", "v65"} },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, {"v60", "v62", "v65"} },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, {"v60", "v62", "v65"} },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, {"v60", "v62", "v65"} },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, {"v60", "v62", "v65"} },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vnot, {"v60", "v62", "v65"} },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, {"v60", "v62", "v65"} },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vor, {"v60", "v62", "v65"} },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, {"v60", "v62", "v65"} },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, {"v60", "v62", "v65"} },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, {"v60", "v62", "v65"} },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, {"v60", "v62", "v65"} },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, {"v60", "v62", "v65"} },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, {"v60", "v62", "v65"} },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, {"v60", "v62", "v65"} },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, {"v60", "v62", "v65"} },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, {"v60", "v62", "v65"} },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, {"v60", "v62", "v65"} },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, {"v60", "v62", "v65"} },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, {"v60", "v62", "v65"} },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, {"v60", "v62", "v65"} },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, {"v60", "v62", "v65"} },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, {"v60", "v62", "v65"} },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, {"v60", "v62", "v65"} },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, {"v60", "v62", "v65"} },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, {"v60", "v62", "v65"} },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, {"v60", "v62", "v65"} },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, {"v65"} },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, {"v65"} },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, {"v65"} },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, {"v65"} },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, {"v65"} },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, {"v65"} },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, {"v60", "v62", "v65"} },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, {"v60", "v62", "v65"} },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, {"v65"} },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, {"v65"} },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, {"v65"} },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, {"v65"} },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, {"v60", "v62", "v65"} },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, {"v60", "v62", "v65"} },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, {"v60", "v62", "v65"} },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, {"v60", "v62", "v65"} },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {"v60", "v62", "v65"} },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {"v60", "v62", "v65"} },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {"v60", "v62", "v65"} },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, {"v60", "v62", "v65"} },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, {"v60", "v62", "v65"} },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, {"v60", "v62", "v65"} },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, {"v60", "v62", "v65"} },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, {"v60", "v62", "v65"} },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, {"v60", "v62", "v65"} },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, {"v60", "v62", "v65"} },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, {"v60", "v62", "v65"} },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, {"v60", "v62", "v65"} },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, {"v60", "v62", "v65"} },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, {"v60", "v62", "v65"} },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, {"v60", "v62", "v65"} },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, {"v60", "v62", "v65"} },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {"v60", "v62", "v65"} },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {"v60", "v62", "v65"} },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {"v60", "v62", "v65"} },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, {"v60", "v62", "v65"} },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, {"v65"} },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, {"v65"} },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, {"v65"} },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, {"v65"} },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, {"v60", "v62", "v65"} },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, {"v60", "v62", "v65"} },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, {"v60", "v62", "v65"} },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, {"v60", "v62", "v65"} },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vror, {"v60", "v62", "v65"} },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, {"v60", "v62", "v65"} },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, {"v60", "v62", "v65"} },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, {"v60", "v62", "v65"} },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, {"v60", "v62", "v65"} },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, {"v60", "v62", "v65"} },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, {"v62", "v65"} },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, {"v62", "v65"} },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, {"v62", "v65"} },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, {"v62", "v65"} },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, {"v60", "v62", "v65"} },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, {"v60", "v62", "v65"} },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, {"v60", "v62", "v65"} },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, {"v60", "v62", "v65"} },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {"v60", "v62", "v65"} },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {"v60", "v62", "v65"} },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {"v60", "v62", "v65"} },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, {"v60", "v62", "v65"} },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, {"v60", "v62", "v65"} },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, {"v60", "v62", "v65"} },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, {"v62", "v65"} },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, {"v62", "v65"} },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, {"v60", "v62", "v65"} },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, {"v60", "v62", "v65"} },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vsb, {"v60", "v62", "v65"} },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, {"v60", "v62", "v65"} },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vsh, {"v60", "v62", "v65"} },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, {"v60", "v62", "v65"} },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, {"v60", "v62", "v65"} },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, {"v60", "v62", "v65"} },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, {"v60", "v62", "v65"} },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, {"v60", "v62", "v65"} },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, {"v60", "v62", "v65"} },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, {"v60", "v62", "v65"} },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, {"v60", "v62", "v65"} },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, {"v60", "v62", "v65"} },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, {"v60", "v62", "v65"} },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, {"v60", "v62", "v65"} },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, {"v60", "v62", "v65"} },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, {"v60", "v62", "v65"} },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, {"v60", "v62", "v65"} },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, {"v60", "v62", "v65"} },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, {"v60", "v62", "v65"} },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, {"v60", "v62", "v65"} },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, {"v60", "v62", "v65"} },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, {"v60", "v62", "v65"} },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, {"v60", "v62", "v65"} },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, {"v60", "v62", "v65"} },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, {"v60", "v62", "v65"} },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, {"v60", "v62", "v65"} },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, {"v62", "v65"} },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, {"v62", "v65"} },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, {"v62", "v65"} },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, {"v62", "v65"} },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, {"v62", "v65"} },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, {"v62", "v65"} },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, {"v60", "v62", "v65"} },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, {"v60", "v62", "v65"} },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, {"v60", "v62", "v65"} },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, {"v60", "v62", "v65"} },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, {"v60", "v62", "v65"} },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, {"v60", "v62", "v65"} },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, {"v60", "v62", "v65"} },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, {"v60", "v62", "v65"} },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, {"v60", "v62", "v65"} },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, {"v60", "v62", "v65"} },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, {"v60", "v62", "v65"} },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, {"v60", "v62", "v65"} },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, {"v60", "v62", "v65"} },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, {"v60", "v62", "v65"} },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, {"v60", "v62", "v65"} },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, {"v60", "v62", "v65"} },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, {"v62", "v65"} },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, {"v62", "v65"} },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, {"v60", "v62", "v65"} },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, {"v60", "v62", "v65"} },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, {"v60", "v62", "v65"} },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, {"v60", "v62", "v65"} },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, {"v60", "v62", "v65"} },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, {"v60", "v62", "v65"} },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, {"v62", "v65"} },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, {"v62", "v65"} },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, {"v62", "v65"} },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, {"v62", "v65"} },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, {"v60", "v62", "v65"} },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, {"v60", "v62", "v65"} },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, {"v60", "v62", "v65"} },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, {"v60", "v62", "v65"} },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, {"v60", "v62", "v65"} },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, {"v60", "v62", "v65"} },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, {"v60", "v62", "v65"} },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, {"v60", "v62", "v65"} },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vswap, {"v60", "v62", "v65"} },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, {"v60", "v62", "v65"} },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, {"v60", "v62", "v65"} },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, {"v60", "v62", "v65"} },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, {"v60", "v62", "v65"} },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, {"v60", "v62", "v65"} },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, {"v60", "v62", "v65"} },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, {"v60", "v62", "v65"} },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, {"v60", "v62", "v65"} },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, {"v60", "v62", "v65"} },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, {"v60", "v62", "v65"} },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, {"v60", "v62", "v65"} },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, {"v60", "v62", "v65"} },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, {"v60", "v62", "v65"} },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, {"v60", "v62", "v65"} },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, {"v60", "v62", "v65"} },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, {"v60", "v62", "v65"} },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, {"v60", "v62", "v65"} },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, {"v60", "v62", "v65"} },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, {"v60", "v62", "v65"} },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, {"v60", "v62", "v65"} },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, {"v60", "v62", "v65"} },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, {"v60", "v62", "v65"} },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, {"v60", "v62", "v65"} },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, {"v60", "v62", "v65"} },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, {"v60", "v62", "v65"} },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vxor, {"v60", "v62", "v65"} },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, {"v60", "v62", "v65"} },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vzb, {"v60", "v62", "v65"} },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, {"v60", "v62", "v65"} },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vzh, {"v60", "v62", "v65"} },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, {"v60", "v62", "v65"} },
2515   };
2516 
2517   const TargetInfo &TI = Context.getTargetInfo();
2518 
2519   auto FC = ValidCPU.find(BuiltinID);
2520   if (FC != ValidCPU.end()) {
2521     const TargetOptions &Opts = TI.getTargetOpts();
2522     StringRef CPU = Opts.CPU;
2523     if (!CPU.empty()) {
2524       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2525       CPU.consume_front("hexagon");
2526       if (llvm::none_of(FC->second, [CPU](StringRef S) { return S == CPU; }))
2527         return Diag(TheCall->getBeginLoc(),
2528                     diag::err_hexagon_builtin_unsupported_cpu);
2529     }
2530   }
2531 
2532   auto FH = ValidHVX.find(BuiltinID);
2533   if (FH != ValidHVX.end()) {
2534     if (!TI.hasFeature("hvx"))
2535       return Diag(TheCall->getBeginLoc(),
2536                   diag::err_hexagon_builtin_requires_hvx);
2537 
2538     bool IsValid = llvm::any_of(FH->second,
2539                                 [&TI] (StringRef V) {
2540                                   std::string F = "hvx" + V.str();
2541                                   return TI.hasFeature(F);
2542                                 });
2543     if (!IsValid)
2544       return Diag(TheCall->getBeginLoc(),
2545                   diag::err_hexagon_builtin_unsupported_hvx);
2546   }
2547 
2548   return false;
2549 }
2550 
2551 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2552   struct ArgInfo {
2553     ArgInfo(unsigned O, bool S, unsigned W, unsigned A)
2554       : OpNum(O), IsSigned(S), BitWidth(W), Align(A) {}
2555     unsigned OpNum = 0;
2556     bool IsSigned = false;
2557     unsigned BitWidth = 0;
2558     unsigned Align = 0;
2559   };
2560 
2561   static const std::map<unsigned, std::vector<ArgInfo>> Infos = {
2562     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2563     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2564     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2565     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2566     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2567     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2568     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2569     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2570     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2571     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2572     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2573 
2574     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2575     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2576     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2577     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2578     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2579     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2580     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2581     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2582     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2583     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2584     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2585 
2586     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2587     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2588     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2589     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2590     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2591     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2592     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2593     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2594     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2595     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2596     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2597     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2598     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2599     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2600     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2601     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2602     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2603     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2604     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2605     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2606     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2607     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2608     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2609     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2610     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2611     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2612     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2613     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2614     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2615     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2616     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2617     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2618     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2619     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2620     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2621     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2622     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2623     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2624     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2625     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2626     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2627     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2628     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2629     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2630     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2631     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2632     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2633     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2634     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2635     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2636     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2637     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2638                                                       {{ 1, false, 6,  0 }} },
2639     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2640     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2641     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2642     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2643     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2644     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2645     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2646                                                       {{ 1, false, 5,  0 }} },
2647     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2648     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2649     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2650     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2651     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2652     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2653                                                        { 2, false, 5,  0 }} },
2654     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2655                                                        { 2, false, 6,  0 }} },
2656     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2657                                                        { 3, false, 5,  0 }} },
2658     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2659                                                        { 3, false, 6,  0 }} },
2660     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2661     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2662     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2663     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2664     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2665     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2666     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2667     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2668     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2669     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2670     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2671     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2672     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2673     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2674     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2675     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2676                                                       {{ 2, false, 4,  0 },
2677                                                        { 3, false, 5,  0 }} },
2678     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2679                                                       {{ 2, false, 4,  0 },
2680                                                        { 3, false, 5,  0 }} },
2681     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2682                                                       {{ 2, false, 4,  0 },
2683                                                        { 3, false, 5,  0 }} },
2684     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2685                                                       {{ 2, false, 4,  0 },
2686                                                        { 3, false, 5,  0 }} },
2687     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2688     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2689     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2690     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2691     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2692     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2693     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2694     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2695     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2696     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2697     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2698                                                        { 2, false, 5,  0 }} },
2699     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2700                                                        { 2, false, 6,  0 }} },
2701     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2702     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2703     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2704     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2705     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2706     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2707     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2708     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2709     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2710                                                       {{ 1, false, 4,  0 }} },
2711     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2712     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2713                                                       {{ 1, false, 4,  0 }} },
2714     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2715     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2716     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2717     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2718     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2719     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2720     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2721     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2722     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2723     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2724     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2725     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2726     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2727     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2728     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2729     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2730     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2731     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2732     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2733     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2734                                                       {{ 3, false, 1,  0 }} },
2735     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2736     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2737     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2738     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2739                                                       {{ 3, false, 1,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2741     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2742     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2743     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2744                                                       {{ 3, false, 1,  0 }} },
2745   };
2746 
2747   auto F = Infos.find(BuiltinID);
2748   if (F == Infos.end())
2749     return false;
2750 
2751   bool Error = false;
2752 
2753   for (const ArgInfo &A : F->second) {
2754     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth-1)) : 0;
2755     int32_t Max = (1 << (A.IsSigned ? A.BitWidth-1 : A.BitWidth)) - 1;
2756     if (!A.Align) {
2757       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2758     } else {
2759       unsigned M = 1 << A.Align;
2760       Min *= M;
2761       Max *= M;
2762       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2763                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2764     }
2765   }
2766   return Error;
2767 }
2768 
2769 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2770                                            CallExpr *TheCall) {
2771   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2772          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2773 }
2774 
2775 
2776 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2777 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2778 // ordering for DSP is unspecified. MSA is ordered by the data format used
2779 // by the underlying instruction i.e., df/m, df/n and then by size.
2780 //
2781 // FIXME: The size tests here should instead be tablegen'd along with the
2782 //        definitions from include/clang/Basic/BuiltinsMips.def.
2783 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2784 //        be too.
2785 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2786   unsigned i = 0, l = 0, u = 0, m = 0;
2787   switch (BuiltinID) {
2788   default: return false;
2789   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2790   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2791   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2792   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2793   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2794   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2795   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2796   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
2797   // df/m field.
2798   // These intrinsics take an unsigned 3 bit immediate.
2799   case Mips::BI__builtin_msa_bclri_b:
2800   case Mips::BI__builtin_msa_bnegi_b:
2801   case Mips::BI__builtin_msa_bseti_b:
2802   case Mips::BI__builtin_msa_sat_s_b:
2803   case Mips::BI__builtin_msa_sat_u_b:
2804   case Mips::BI__builtin_msa_slli_b:
2805   case Mips::BI__builtin_msa_srai_b:
2806   case Mips::BI__builtin_msa_srari_b:
2807   case Mips::BI__builtin_msa_srli_b:
2808   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
2809   case Mips::BI__builtin_msa_binsli_b:
2810   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
2811   // These intrinsics take an unsigned 4 bit immediate.
2812   case Mips::BI__builtin_msa_bclri_h:
2813   case Mips::BI__builtin_msa_bnegi_h:
2814   case Mips::BI__builtin_msa_bseti_h:
2815   case Mips::BI__builtin_msa_sat_s_h:
2816   case Mips::BI__builtin_msa_sat_u_h:
2817   case Mips::BI__builtin_msa_slli_h:
2818   case Mips::BI__builtin_msa_srai_h:
2819   case Mips::BI__builtin_msa_srari_h:
2820   case Mips::BI__builtin_msa_srli_h:
2821   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
2822   case Mips::BI__builtin_msa_binsli_h:
2823   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
2824   // These intrinsics take an unsigned 5 bit immediate.
2825   // The first block of intrinsics actually have an unsigned 5 bit field,
2826   // not a df/n field.
2827   case Mips::BI__builtin_msa_clei_u_b:
2828   case Mips::BI__builtin_msa_clei_u_h:
2829   case Mips::BI__builtin_msa_clei_u_w:
2830   case Mips::BI__builtin_msa_clei_u_d:
2831   case Mips::BI__builtin_msa_clti_u_b:
2832   case Mips::BI__builtin_msa_clti_u_h:
2833   case Mips::BI__builtin_msa_clti_u_w:
2834   case Mips::BI__builtin_msa_clti_u_d:
2835   case Mips::BI__builtin_msa_maxi_u_b:
2836   case Mips::BI__builtin_msa_maxi_u_h:
2837   case Mips::BI__builtin_msa_maxi_u_w:
2838   case Mips::BI__builtin_msa_maxi_u_d:
2839   case Mips::BI__builtin_msa_mini_u_b:
2840   case Mips::BI__builtin_msa_mini_u_h:
2841   case Mips::BI__builtin_msa_mini_u_w:
2842   case Mips::BI__builtin_msa_mini_u_d:
2843   case Mips::BI__builtin_msa_addvi_b:
2844   case Mips::BI__builtin_msa_addvi_h:
2845   case Mips::BI__builtin_msa_addvi_w:
2846   case Mips::BI__builtin_msa_addvi_d:
2847   case Mips::BI__builtin_msa_bclri_w:
2848   case Mips::BI__builtin_msa_bnegi_w:
2849   case Mips::BI__builtin_msa_bseti_w:
2850   case Mips::BI__builtin_msa_sat_s_w:
2851   case Mips::BI__builtin_msa_sat_u_w:
2852   case Mips::BI__builtin_msa_slli_w:
2853   case Mips::BI__builtin_msa_srai_w:
2854   case Mips::BI__builtin_msa_srari_w:
2855   case Mips::BI__builtin_msa_srli_w:
2856   case Mips::BI__builtin_msa_srlri_w:
2857   case Mips::BI__builtin_msa_subvi_b:
2858   case Mips::BI__builtin_msa_subvi_h:
2859   case Mips::BI__builtin_msa_subvi_w:
2860   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
2861   case Mips::BI__builtin_msa_binsli_w:
2862   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
2863   // These intrinsics take an unsigned 6 bit immediate.
2864   case Mips::BI__builtin_msa_bclri_d:
2865   case Mips::BI__builtin_msa_bnegi_d:
2866   case Mips::BI__builtin_msa_bseti_d:
2867   case Mips::BI__builtin_msa_sat_s_d:
2868   case Mips::BI__builtin_msa_sat_u_d:
2869   case Mips::BI__builtin_msa_slli_d:
2870   case Mips::BI__builtin_msa_srai_d:
2871   case Mips::BI__builtin_msa_srari_d:
2872   case Mips::BI__builtin_msa_srli_d:
2873   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
2874   case Mips::BI__builtin_msa_binsli_d:
2875   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
2876   // These intrinsics take a signed 5 bit immediate.
2877   case Mips::BI__builtin_msa_ceqi_b:
2878   case Mips::BI__builtin_msa_ceqi_h:
2879   case Mips::BI__builtin_msa_ceqi_w:
2880   case Mips::BI__builtin_msa_ceqi_d:
2881   case Mips::BI__builtin_msa_clti_s_b:
2882   case Mips::BI__builtin_msa_clti_s_h:
2883   case Mips::BI__builtin_msa_clti_s_w:
2884   case Mips::BI__builtin_msa_clti_s_d:
2885   case Mips::BI__builtin_msa_clei_s_b:
2886   case Mips::BI__builtin_msa_clei_s_h:
2887   case Mips::BI__builtin_msa_clei_s_w:
2888   case Mips::BI__builtin_msa_clei_s_d:
2889   case Mips::BI__builtin_msa_maxi_s_b:
2890   case Mips::BI__builtin_msa_maxi_s_h:
2891   case Mips::BI__builtin_msa_maxi_s_w:
2892   case Mips::BI__builtin_msa_maxi_s_d:
2893   case Mips::BI__builtin_msa_mini_s_b:
2894   case Mips::BI__builtin_msa_mini_s_h:
2895   case Mips::BI__builtin_msa_mini_s_w:
2896   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
2897   // These intrinsics take an unsigned 8 bit immediate.
2898   case Mips::BI__builtin_msa_andi_b:
2899   case Mips::BI__builtin_msa_nori_b:
2900   case Mips::BI__builtin_msa_ori_b:
2901   case Mips::BI__builtin_msa_shf_b:
2902   case Mips::BI__builtin_msa_shf_h:
2903   case Mips::BI__builtin_msa_shf_w:
2904   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
2905   case Mips::BI__builtin_msa_bseli_b:
2906   case Mips::BI__builtin_msa_bmnzi_b:
2907   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
2908   // df/n format
2909   // These intrinsics take an unsigned 4 bit immediate.
2910   case Mips::BI__builtin_msa_copy_s_b:
2911   case Mips::BI__builtin_msa_copy_u_b:
2912   case Mips::BI__builtin_msa_insve_b:
2913   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
2914   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
2915   // These intrinsics take an unsigned 3 bit immediate.
2916   case Mips::BI__builtin_msa_copy_s_h:
2917   case Mips::BI__builtin_msa_copy_u_h:
2918   case Mips::BI__builtin_msa_insve_h:
2919   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
2920   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
2921   // These intrinsics take an unsigned 2 bit immediate.
2922   case Mips::BI__builtin_msa_copy_s_w:
2923   case Mips::BI__builtin_msa_copy_u_w:
2924   case Mips::BI__builtin_msa_insve_w:
2925   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
2926   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
2927   // These intrinsics take an unsigned 1 bit immediate.
2928   case Mips::BI__builtin_msa_copy_s_d:
2929   case Mips::BI__builtin_msa_copy_u_d:
2930   case Mips::BI__builtin_msa_insve_d:
2931   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
2932   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
2933   // Memory offsets and immediate loads.
2934   // These intrinsics take a signed 10 bit immediate.
2935   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
2936   case Mips::BI__builtin_msa_ldi_h:
2937   case Mips::BI__builtin_msa_ldi_w:
2938   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
2939   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
2940   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
2941   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
2942   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
2943   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
2944   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
2945   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
2946   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
2947   }
2948 
2949   if (!m)
2950     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2951 
2952   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
2953          SemaBuiltinConstantArgMultiple(TheCall, i, m);
2954 }
2955 
2956 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2957   unsigned i = 0, l = 0, u = 0;
2958   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
2959                       BuiltinID == PPC::BI__builtin_divdeu ||
2960                       BuiltinID == PPC::BI__builtin_bpermd;
2961   bool IsTarget64Bit = Context.getTargetInfo()
2962                               .getTypeWidth(Context
2963                                             .getTargetInfo()
2964                                             .getIntPtrType()) == 64;
2965   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
2966                        BuiltinID == PPC::BI__builtin_divweu ||
2967                        BuiltinID == PPC::BI__builtin_divde ||
2968                        BuiltinID == PPC::BI__builtin_divdeu;
2969 
2970   if (Is64BitBltin && !IsTarget64Bit)
2971     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
2972            << TheCall->getSourceRange();
2973 
2974   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
2975       (BuiltinID == PPC::BI__builtin_bpermd &&
2976        !Context.getTargetInfo().hasFeature("bpermd")))
2977     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2978            << TheCall->getSourceRange();
2979 
2980   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
2981     if (!Context.getTargetInfo().hasFeature("vsx"))
2982       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
2983              << TheCall->getSourceRange();
2984     return false;
2985   };
2986 
2987   switch (BuiltinID) {
2988   default: return false;
2989   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
2990   case PPC::BI__builtin_altivec_crypto_vshasigmad:
2991     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2992            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
2993   case PPC::BI__builtin_tbegin:
2994   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
2995   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
2996   case PPC::BI__builtin_tabortwc:
2997   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
2998   case PPC::BI__builtin_tabortwci:
2999   case PPC::BI__builtin_tabortdci:
3000     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3001            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3002   case PPC::BI__builtin_vsx_xxpermdi:
3003   case PPC::BI__builtin_vsx_xxsldwi:
3004     return SemaBuiltinVSX(TheCall);
3005   case PPC::BI__builtin_unpack_vector_int128:
3006     return SemaVSXCheck(TheCall) ||
3007            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3008   case PPC::BI__builtin_pack_vector_int128:
3009     return SemaVSXCheck(TheCall);
3010   }
3011   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3012 }
3013 
3014 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3015                                            CallExpr *TheCall) {
3016   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3017     Expr *Arg = TheCall->getArg(0);
3018     llvm::APSInt AbortCode(32);
3019     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3020         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3021       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3022              << Arg->getSourceRange();
3023   }
3024 
3025   // For intrinsics which take an immediate value as part of the instruction,
3026   // range check them here.
3027   unsigned i = 0, l = 0, u = 0;
3028   switch (BuiltinID) {
3029   default: return false;
3030   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3031   case SystemZ::BI__builtin_s390_verimb:
3032   case SystemZ::BI__builtin_s390_verimh:
3033   case SystemZ::BI__builtin_s390_verimf:
3034   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3035   case SystemZ::BI__builtin_s390_vfaeb:
3036   case SystemZ::BI__builtin_s390_vfaeh:
3037   case SystemZ::BI__builtin_s390_vfaef:
3038   case SystemZ::BI__builtin_s390_vfaebs:
3039   case SystemZ::BI__builtin_s390_vfaehs:
3040   case SystemZ::BI__builtin_s390_vfaefs:
3041   case SystemZ::BI__builtin_s390_vfaezb:
3042   case SystemZ::BI__builtin_s390_vfaezh:
3043   case SystemZ::BI__builtin_s390_vfaezf:
3044   case SystemZ::BI__builtin_s390_vfaezbs:
3045   case SystemZ::BI__builtin_s390_vfaezhs:
3046   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3047   case SystemZ::BI__builtin_s390_vfisb:
3048   case SystemZ::BI__builtin_s390_vfidb:
3049     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3050            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3051   case SystemZ::BI__builtin_s390_vftcisb:
3052   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3053   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3054   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3055   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3056   case SystemZ::BI__builtin_s390_vstrcb:
3057   case SystemZ::BI__builtin_s390_vstrch:
3058   case SystemZ::BI__builtin_s390_vstrcf:
3059   case SystemZ::BI__builtin_s390_vstrczb:
3060   case SystemZ::BI__builtin_s390_vstrczh:
3061   case SystemZ::BI__builtin_s390_vstrczf:
3062   case SystemZ::BI__builtin_s390_vstrcbs:
3063   case SystemZ::BI__builtin_s390_vstrchs:
3064   case SystemZ::BI__builtin_s390_vstrcfs:
3065   case SystemZ::BI__builtin_s390_vstrczbs:
3066   case SystemZ::BI__builtin_s390_vstrczhs:
3067   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3068   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3069   case SystemZ::BI__builtin_s390_vfminsb:
3070   case SystemZ::BI__builtin_s390_vfmaxsb:
3071   case SystemZ::BI__builtin_s390_vfmindb:
3072   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3073   }
3074   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3075 }
3076 
3077 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3078 /// This checks that the target supports __builtin_cpu_supports and
3079 /// that the string argument is constant and valid.
3080 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3081   Expr *Arg = TheCall->getArg(0);
3082 
3083   // Check if the argument is a string literal.
3084   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3085     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3086            << Arg->getSourceRange();
3087 
3088   // Check the contents of the string.
3089   StringRef Feature =
3090       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3091   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3092     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3093            << Arg->getSourceRange();
3094   return false;
3095 }
3096 
3097 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3098 /// This checks that the target supports __builtin_cpu_is and
3099 /// that the string argument is constant and valid.
3100 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3101   Expr *Arg = TheCall->getArg(0);
3102 
3103   // Check if the argument is a string literal.
3104   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3105     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3106            << Arg->getSourceRange();
3107 
3108   // Check the contents of the string.
3109   StringRef Feature =
3110       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3111   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3112     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3113            << Arg->getSourceRange();
3114   return false;
3115 }
3116 
3117 // Check if the rounding mode is legal.
3118 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3119   // Indicates if this instruction has rounding control or just SAE.
3120   bool HasRC = false;
3121 
3122   unsigned ArgNum = 0;
3123   switch (BuiltinID) {
3124   default:
3125     return false;
3126   case X86::BI__builtin_ia32_vcvttsd2si32:
3127   case X86::BI__builtin_ia32_vcvttsd2si64:
3128   case X86::BI__builtin_ia32_vcvttsd2usi32:
3129   case X86::BI__builtin_ia32_vcvttsd2usi64:
3130   case X86::BI__builtin_ia32_vcvttss2si32:
3131   case X86::BI__builtin_ia32_vcvttss2si64:
3132   case X86::BI__builtin_ia32_vcvttss2usi32:
3133   case X86::BI__builtin_ia32_vcvttss2usi64:
3134     ArgNum = 1;
3135     break;
3136   case X86::BI__builtin_ia32_maxpd512:
3137   case X86::BI__builtin_ia32_maxps512:
3138   case X86::BI__builtin_ia32_minpd512:
3139   case X86::BI__builtin_ia32_minps512:
3140     ArgNum = 2;
3141     break;
3142   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3143   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3144   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3145   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3146   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3147   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3148   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3149   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3150   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3151   case X86::BI__builtin_ia32_exp2pd_mask:
3152   case X86::BI__builtin_ia32_exp2ps_mask:
3153   case X86::BI__builtin_ia32_getexppd512_mask:
3154   case X86::BI__builtin_ia32_getexpps512_mask:
3155   case X86::BI__builtin_ia32_rcp28pd_mask:
3156   case X86::BI__builtin_ia32_rcp28ps_mask:
3157   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3158   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3159   case X86::BI__builtin_ia32_vcomisd:
3160   case X86::BI__builtin_ia32_vcomiss:
3161   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3162     ArgNum = 3;
3163     break;
3164   case X86::BI__builtin_ia32_cmppd512_mask:
3165   case X86::BI__builtin_ia32_cmpps512_mask:
3166   case X86::BI__builtin_ia32_cmpsd_mask:
3167   case X86::BI__builtin_ia32_cmpss_mask:
3168   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3169   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3170   case X86::BI__builtin_ia32_getexpss128_round_mask:
3171   case X86::BI__builtin_ia32_maxsd_round_mask:
3172   case X86::BI__builtin_ia32_maxss_round_mask:
3173   case X86::BI__builtin_ia32_minsd_round_mask:
3174   case X86::BI__builtin_ia32_minss_round_mask:
3175   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3176   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3177   case X86::BI__builtin_ia32_reducepd512_mask:
3178   case X86::BI__builtin_ia32_reduceps512_mask:
3179   case X86::BI__builtin_ia32_rndscalepd_mask:
3180   case X86::BI__builtin_ia32_rndscaleps_mask:
3181   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3182   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3183     ArgNum = 4;
3184     break;
3185   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3186   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3187   case X86::BI__builtin_ia32_fixupimmps512_mask:
3188   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3189   case X86::BI__builtin_ia32_fixupimmsd_mask:
3190   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3191   case X86::BI__builtin_ia32_fixupimmss_mask:
3192   case X86::BI__builtin_ia32_fixupimmss_maskz:
3193   case X86::BI__builtin_ia32_rangepd512_mask:
3194   case X86::BI__builtin_ia32_rangeps512_mask:
3195   case X86::BI__builtin_ia32_rangesd128_round_mask:
3196   case X86::BI__builtin_ia32_rangess128_round_mask:
3197   case X86::BI__builtin_ia32_reducesd_mask:
3198   case X86::BI__builtin_ia32_reducess_mask:
3199   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3200   case X86::BI__builtin_ia32_rndscaless_round_mask:
3201     ArgNum = 5;
3202     break;
3203   case X86::BI__builtin_ia32_vcvtsd2si64:
3204   case X86::BI__builtin_ia32_vcvtsd2si32:
3205   case X86::BI__builtin_ia32_vcvtsd2usi32:
3206   case X86::BI__builtin_ia32_vcvtsd2usi64:
3207   case X86::BI__builtin_ia32_vcvtss2si32:
3208   case X86::BI__builtin_ia32_vcvtss2si64:
3209   case X86::BI__builtin_ia32_vcvtss2usi32:
3210   case X86::BI__builtin_ia32_vcvtss2usi64:
3211   case X86::BI__builtin_ia32_sqrtpd512:
3212   case X86::BI__builtin_ia32_sqrtps512:
3213     ArgNum = 1;
3214     HasRC = true;
3215     break;
3216   case X86::BI__builtin_ia32_addpd512:
3217   case X86::BI__builtin_ia32_addps512:
3218   case X86::BI__builtin_ia32_divpd512:
3219   case X86::BI__builtin_ia32_divps512:
3220   case X86::BI__builtin_ia32_mulpd512:
3221   case X86::BI__builtin_ia32_mulps512:
3222   case X86::BI__builtin_ia32_subpd512:
3223   case X86::BI__builtin_ia32_subps512:
3224   case X86::BI__builtin_ia32_cvtsi2sd64:
3225   case X86::BI__builtin_ia32_cvtsi2ss32:
3226   case X86::BI__builtin_ia32_cvtsi2ss64:
3227   case X86::BI__builtin_ia32_cvtusi2sd64:
3228   case X86::BI__builtin_ia32_cvtusi2ss32:
3229   case X86::BI__builtin_ia32_cvtusi2ss64:
3230     ArgNum = 2;
3231     HasRC = true;
3232     break;
3233   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3234   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3235   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3236   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3237   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3238   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3239   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3240   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3241   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3242   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3243   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3244     ArgNum = 3;
3245     HasRC = true;
3246     break;
3247   case X86::BI__builtin_ia32_addss_round_mask:
3248   case X86::BI__builtin_ia32_addsd_round_mask:
3249   case X86::BI__builtin_ia32_divss_round_mask:
3250   case X86::BI__builtin_ia32_divsd_round_mask:
3251   case X86::BI__builtin_ia32_mulss_round_mask:
3252   case X86::BI__builtin_ia32_mulsd_round_mask:
3253   case X86::BI__builtin_ia32_subss_round_mask:
3254   case X86::BI__builtin_ia32_subsd_round_mask:
3255   case X86::BI__builtin_ia32_scalefpd512_mask:
3256   case X86::BI__builtin_ia32_scalefps512_mask:
3257   case X86::BI__builtin_ia32_scalefsd_round_mask:
3258   case X86::BI__builtin_ia32_scalefss_round_mask:
3259   case X86::BI__builtin_ia32_getmantpd512_mask:
3260   case X86::BI__builtin_ia32_getmantps512_mask:
3261   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3262   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3263   case X86::BI__builtin_ia32_sqrtss_round_mask:
3264   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3265   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3266   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3267   case X86::BI__builtin_ia32_vfmaddss3_mask:
3268   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3269   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3270   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3271   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3272   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3273   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3274   case X86::BI__builtin_ia32_vfmaddps512_mask:
3275   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3276   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3277   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3278   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3279   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3280   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3281   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3282   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3283   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3284   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3285   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3286     ArgNum = 4;
3287     HasRC = true;
3288     break;
3289   case X86::BI__builtin_ia32_getmantsd_round_mask:
3290   case X86::BI__builtin_ia32_getmantss_round_mask:
3291     ArgNum = 5;
3292     HasRC = true;
3293     break;
3294   }
3295 
3296   llvm::APSInt Result;
3297 
3298   // We can't check the value of a dependent argument.
3299   Expr *Arg = TheCall->getArg(ArgNum);
3300   if (Arg->isTypeDependent() || Arg->isValueDependent())
3301     return false;
3302 
3303   // Check constant-ness first.
3304   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3305     return true;
3306 
3307   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3308   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3309   // combined with ROUND_NO_EXC.
3310   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3311       Result == 8/*ROUND_NO_EXC*/ ||
3312       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3313     return false;
3314 
3315   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3316          << Arg->getSourceRange();
3317 }
3318 
3319 // Check if the gather/scatter scale is legal.
3320 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3321                                              CallExpr *TheCall) {
3322   unsigned ArgNum = 0;
3323   switch (BuiltinID) {
3324   default:
3325     return false;
3326   case X86::BI__builtin_ia32_gatherpfdpd:
3327   case X86::BI__builtin_ia32_gatherpfdps:
3328   case X86::BI__builtin_ia32_gatherpfqpd:
3329   case X86::BI__builtin_ia32_gatherpfqps:
3330   case X86::BI__builtin_ia32_scatterpfdpd:
3331   case X86::BI__builtin_ia32_scatterpfdps:
3332   case X86::BI__builtin_ia32_scatterpfqpd:
3333   case X86::BI__builtin_ia32_scatterpfqps:
3334     ArgNum = 3;
3335     break;
3336   case X86::BI__builtin_ia32_gatherd_pd:
3337   case X86::BI__builtin_ia32_gatherd_pd256:
3338   case X86::BI__builtin_ia32_gatherq_pd:
3339   case X86::BI__builtin_ia32_gatherq_pd256:
3340   case X86::BI__builtin_ia32_gatherd_ps:
3341   case X86::BI__builtin_ia32_gatherd_ps256:
3342   case X86::BI__builtin_ia32_gatherq_ps:
3343   case X86::BI__builtin_ia32_gatherq_ps256:
3344   case X86::BI__builtin_ia32_gatherd_q:
3345   case X86::BI__builtin_ia32_gatherd_q256:
3346   case X86::BI__builtin_ia32_gatherq_q:
3347   case X86::BI__builtin_ia32_gatherq_q256:
3348   case X86::BI__builtin_ia32_gatherd_d:
3349   case X86::BI__builtin_ia32_gatherd_d256:
3350   case X86::BI__builtin_ia32_gatherq_d:
3351   case X86::BI__builtin_ia32_gatherq_d256:
3352   case X86::BI__builtin_ia32_gather3div2df:
3353   case X86::BI__builtin_ia32_gather3div2di:
3354   case X86::BI__builtin_ia32_gather3div4df:
3355   case X86::BI__builtin_ia32_gather3div4di:
3356   case X86::BI__builtin_ia32_gather3div4sf:
3357   case X86::BI__builtin_ia32_gather3div4si:
3358   case X86::BI__builtin_ia32_gather3div8sf:
3359   case X86::BI__builtin_ia32_gather3div8si:
3360   case X86::BI__builtin_ia32_gather3siv2df:
3361   case X86::BI__builtin_ia32_gather3siv2di:
3362   case X86::BI__builtin_ia32_gather3siv4df:
3363   case X86::BI__builtin_ia32_gather3siv4di:
3364   case X86::BI__builtin_ia32_gather3siv4sf:
3365   case X86::BI__builtin_ia32_gather3siv4si:
3366   case X86::BI__builtin_ia32_gather3siv8sf:
3367   case X86::BI__builtin_ia32_gather3siv8si:
3368   case X86::BI__builtin_ia32_gathersiv8df:
3369   case X86::BI__builtin_ia32_gathersiv16sf:
3370   case X86::BI__builtin_ia32_gatherdiv8df:
3371   case X86::BI__builtin_ia32_gatherdiv16sf:
3372   case X86::BI__builtin_ia32_gathersiv8di:
3373   case X86::BI__builtin_ia32_gathersiv16si:
3374   case X86::BI__builtin_ia32_gatherdiv8di:
3375   case X86::BI__builtin_ia32_gatherdiv16si:
3376   case X86::BI__builtin_ia32_scatterdiv2df:
3377   case X86::BI__builtin_ia32_scatterdiv2di:
3378   case X86::BI__builtin_ia32_scatterdiv4df:
3379   case X86::BI__builtin_ia32_scatterdiv4di:
3380   case X86::BI__builtin_ia32_scatterdiv4sf:
3381   case X86::BI__builtin_ia32_scatterdiv4si:
3382   case X86::BI__builtin_ia32_scatterdiv8sf:
3383   case X86::BI__builtin_ia32_scatterdiv8si:
3384   case X86::BI__builtin_ia32_scattersiv2df:
3385   case X86::BI__builtin_ia32_scattersiv2di:
3386   case X86::BI__builtin_ia32_scattersiv4df:
3387   case X86::BI__builtin_ia32_scattersiv4di:
3388   case X86::BI__builtin_ia32_scattersiv4sf:
3389   case X86::BI__builtin_ia32_scattersiv4si:
3390   case X86::BI__builtin_ia32_scattersiv8sf:
3391   case X86::BI__builtin_ia32_scattersiv8si:
3392   case X86::BI__builtin_ia32_scattersiv8df:
3393   case X86::BI__builtin_ia32_scattersiv16sf:
3394   case X86::BI__builtin_ia32_scatterdiv8df:
3395   case X86::BI__builtin_ia32_scatterdiv16sf:
3396   case X86::BI__builtin_ia32_scattersiv8di:
3397   case X86::BI__builtin_ia32_scattersiv16si:
3398   case X86::BI__builtin_ia32_scatterdiv8di:
3399   case X86::BI__builtin_ia32_scatterdiv16si:
3400     ArgNum = 4;
3401     break;
3402   }
3403 
3404   llvm::APSInt Result;
3405 
3406   // We can't check the value of a dependent argument.
3407   Expr *Arg = TheCall->getArg(ArgNum);
3408   if (Arg->isTypeDependent() || Arg->isValueDependent())
3409     return false;
3410 
3411   // Check constant-ness first.
3412   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3413     return true;
3414 
3415   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3416     return false;
3417 
3418   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3419          << Arg->getSourceRange();
3420 }
3421 
3422 static bool isX86_32Builtin(unsigned BuiltinID) {
3423   // These builtins only work on x86-32 targets.
3424   switch (BuiltinID) {
3425   case X86::BI__builtin_ia32_readeflags_u32:
3426   case X86::BI__builtin_ia32_writeeflags_u32:
3427     return true;
3428   }
3429 
3430   return false;
3431 }
3432 
3433 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3434   if (BuiltinID == X86::BI__builtin_cpu_supports)
3435     return SemaBuiltinCpuSupports(*this, TheCall);
3436 
3437   if (BuiltinID == X86::BI__builtin_cpu_is)
3438     return SemaBuiltinCpuIs(*this, TheCall);
3439 
3440   // Check for 32-bit only builtins on a 64-bit target.
3441   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3442   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3443     return Diag(TheCall->getCallee()->getBeginLoc(),
3444                 diag::err_32_bit_builtin_64_bit_tgt);
3445 
3446   // If the intrinsic has rounding or SAE make sure its valid.
3447   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3448     return true;
3449 
3450   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3451   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3452     return true;
3453 
3454   // For intrinsics which take an immediate value as part of the instruction,
3455   // range check them here.
3456   int i = 0, l = 0, u = 0;
3457   switch (BuiltinID) {
3458   default:
3459     return false;
3460   case X86::BI__builtin_ia32_vec_ext_v2si:
3461   case X86::BI__builtin_ia32_vec_ext_v2di:
3462   case X86::BI__builtin_ia32_vextractf128_pd256:
3463   case X86::BI__builtin_ia32_vextractf128_ps256:
3464   case X86::BI__builtin_ia32_vextractf128_si256:
3465   case X86::BI__builtin_ia32_extract128i256:
3466   case X86::BI__builtin_ia32_extractf64x4_mask:
3467   case X86::BI__builtin_ia32_extracti64x4_mask:
3468   case X86::BI__builtin_ia32_extractf32x8_mask:
3469   case X86::BI__builtin_ia32_extracti32x8_mask:
3470   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3471   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3472   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3473   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3474     i = 1; l = 0; u = 1;
3475     break;
3476   case X86::BI__builtin_ia32_vec_set_v2di:
3477   case X86::BI__builtin_ia32_vinsertf128_pd256:
3478   case X86::BI__builtin_ia32_vinsertf128_ps256:
3479   case X86::BI__builtin_ia32_vinsertf128_si256:
3480   case X86::BI__builtin_ia32_insert128i256:
3481   case X86::BI__builtin_ia32_insertf32x8:
3482   case X86::BI__builtin_ia32_inserti32x8:
3483   case X86::BI__builtin_ia32_insertf64x4:
3484   case X86::BI__builtin_ia32_inserti64x4:
3485   case X86::BI__builtin_ia32_insertf64x2_256:
3486   case X86::BI__builtin_ia32_inserti64x2_256:
3487   case X86::BI__builtin_ia32_insertf32x4_256:
3488   case X86::BI__builtin_ia32_inserti32x4_256:
3489     i = 2; l = 0; u = 1;
3490     break;
3491   case X86::BI__builtin_ia32_vpermilpd:
3492   case X86::BI__builtin_ia32_vec_ext_v4hi:
3493   case X86::BI__builtin_ia32_vec_ext_v4si:
3494   case X86::BI__builtin_ia32_vec_ext_v4sf:
3495   case X86::BI__builtin_ia32_vec_ext_v4di:
3496   case X86::BI__builtin_ia32_extractf32x4_mask:
3497   case X86::BI__builtin_ia32_extracti32x4_mask:
3498   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3499   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3500     i = 1; l = 0; u = 3;
3501     break;
3502   case X86::BI_mm_prefetch:
3503   case X86::BI__builtin_ia32_vec_ext_v8hi:
3504   case X86::BI__builtin_ia32_vec_ext_v8si:
3505     i = 1; l = 0; u = 7;
3506     break;
3507   case X86::BI__builtin_ia32_sha1rnds4:
3508   case X86::BI__builtin_ia32_blendpd:
3509   case X86::BI__builtin_ia32_shufpd:
3510   case X86::BI__builtin_ia32_vec_set_v4hi:
3511   case X86::BI__builtin_ia32_vec_set_v4si:
3512   case X86::BI__builtin_ia32_vec_set_v4di:
3513   case X86::BI__builtin_ia32_shuf_f32x4_256:
3514   case X86::BI__builtin_ia32_shuf_f64x2_256:
3515   case X86::BI__builtin_ia32_shuf_i32x4_256:
3516   case X86::BI__builtin_ia32_shuf_i64x2_256:
3517   case X86::BI__builtin_ia32_insertf64x2_512:
3518   case X86::BI__builtin_ia32_inserti64x2_512:
3519   case X86::BI__builtin_ia32_insertf32x4:
3520   case X86::BI__builtin_ia32_inserti32x4:
3521     i = 2; l = 0; u = 3;
3522     break;
3523   case X86::BI__builtin_ia32_vpermil2pd:
3524   case X86::BI__builtin_ia32_vpermil2pd256:
3525   case X86::BI__builtin_ia32_vpermil2ps:
3526   case X86::BI__builtin_ia32_vpermil2ps256:
3527     i = 3; l = 0; u = 3;
3528     break;
3529   case X86::BI__builtin_ia32_cmpb128_mask:
3530   case X86::BI__builtin_ia32_cmpw128_mask:
3531   case X86::BI__builtin_ia32_cmpd128_mask:
3532   case X86::BI__builtin_ia32_cmpq128_mask:
3533   case X86::BI__builtin_ia32_cmpb256_mask:
3534   case X86::BI__builtin_ia32_cmpw256_mask:
3535   case X86::BI__builtin_ia32_cmpd256_mask:
3536   case X86::BI__builtin_ia32_cmpq256_mask:
3537   case X86::BI__builtin_ia32_cmpb512_mask:
3538   case X86::BI__builtin_ia32_cmpw512_mask:
3539   case X86::BI__builtin_ia32_cmpd512_mask:
3540   case X86::BI__builtin_ia32_cmpq512_mask:
3541   case X86::BI__builtin_ia32_ucmpb128_mask:
3542   case X86::BI__builtin_ia32_ucmpw128_mask:
3543   case X86::BI__builtin_ia32_ucmpd128_mask:
3544   case X86::BI__builtin_ia32_ucmpq128_mask:
3545   case X86::BI__builtin_ia32_ucmpb256_mask:
3546   case X86::BI__builtin_ia32_ucmpw256_mask:
3547   case X86::BI__builtin_ia32_ucmpd256_mask:
3548   case X86::BI__builtin_ia32_ucmpq256_mask:
3549   case X86::BI__builtin_ia32_ucmpb512_mask:
3550   case X86::BI__builtin_ia32_ucmpw512_mask:
3551   case X86::BI__builtin_ia32_ucmpd512_mask:
3552   case X86::BI__builtin_ia32_ucmpq512_mask:
3553   case X86::BI__builtin_ia32_vpcomub:
3554   case X86::BI__builtin_ia32_vpcomuw:
3555   case X86::BI__builtin_ia32_vpcomud:
3556   case X86::BI__builtin_ia32_vpcomuq:
3557   case X86::BI__builtin_ia32_vpcomb:
3558   case X86::BI__builtin_ia32_vpcomw:
3559   case X86::BI__builtin_ia32_vpcomd:
3560   case X86::BI__builtin_ia32_vpcomq:
3561   case X86::BI__builtin_ia32_vec_set_v8hi:
3562   case X86::BI__builtin_ia32_vec_set_v8si:
3563     i = 2; l = 0; u = 7;
3564     break;
3565   case X86::BI__builtin_ia32_vpermilpd256:
3566   case X86::BI__builtin_ia32_roundps:
3567   case X86::BI__builtin_ia32_roundpd:
3568   case X86::BI__builtin_ia32_roundps256:
3569   case X86::BI__builtin_ia32_roundpd256:
3570   case X86::BI__builtin_ia32_getmantpd128_mask:
3571   case X86::BI__builtin_ia32_getmantpd256_mask:
3572   case X86::BI__builtin_ia32_getmantps128_mask:
3573   case X86::BI__builtin_ia32_getmantps256_mask:
3574   case X86::BI__builtin_ia32_getmantpd512_mask:
3575   case X86::BI__builtin_ia32_getmantps512_mask:
3576   case X86::BI__builtin_ia32_vec_ext_v16qi:
3577   case X86::BI__builtin_ia32_vec_ext_v16hi:
3578     i = 1; l = 0; u = 15;
3579     break;
3580   case X86::BI__builtin_ia32_pblendd128:
3581   case X86::BI__builtin_ia32_blendps:
3582   case X86::BI__builtin_ia32_blendpd256:
3583   case X86::BI__builtin_ia32_shufpd256:
3584   case X86::BI__builtin_ia32_roundss:
3585   case X86::BI__builtin_ia32_roundsd:
3586   case X86::BI__builtin_ia32_rangepd128_mask:
3587   case X86::BI__builtin_ia32_rangepd256_mask:
3588   case X86::BI__builtin_ia32_rangepd512_mask:
3589   case X86::BI__builtin_ia32_rangeps128_mask:
3590   case X86::BI__builtin_ia32_rangeps256_mask:
3591   case X86::BI__builtin_ia32_rangeps512_mask:
3592   case X86::BI__builtin_ia32_getmantsd_round_mask:
3593   case X86::BI__builtin_ia32_getmantss_round_mask:
3594   case X86::BI__builtin_ia32_vec_set_v16qi:
3595   case X86::BI__builtin_ia32_vec_set_v16hi:
3596     i = 2; l = 0; u = 15;
3597     break;
3598   case X86::BI__builtin_ia32_vec_ext_v32qi:
3599     i = 1; l = 0; u = 31;
3600     break;
3601   case X86::BI__builtin_ia32_cmpps:
3602   case X86::BI__builtin_ia32_cmpss:
3603   case X86::BI__builtin_ia32_cmppd:
3604   case X86::BI__builtin_ia32_cmpsd:
3605   case X86::BI__builtin_ia32_cmpps256:
3606   case X86::BI__builtin_ia32_cmppd256:
3607   case X86::BI__builtin_ia32_cmpps128_mask:
3608   case X86::BI__builtin_ia32_cmppd128_mask:
3609   case X86::BI__builtin_ia32_cmpps256_mask:
3610   case X86::BI__builtin_ia32_cmppd256_mask:
3611   case X86::BI__builtin_ia32_cmpps512_mask:
3612   case X86::BI__builtin_ia32_cmppd512_mask:
3613   case X86::BI__builtin_ia32_cmpsd_mask:
3614   case X86::BI__builtin_ia32_cmpss_mask:
3615   case X86::BI__builtin_ia32_vec_set_v32qi:
3616     i = 2; l = 0; u = 31;
3617     break;
3618   case X86::BI__builtin_ia32_permdf256:
3619   case X86::BI__builtin_ia32_permdi256:
3620   case X86::BI__builtin_ia32_permdf512:
3621   case X86::BI__builtin_ia32_permdi512:
3622   case X86::BI__builtin_ia32_vpermilps:
3623   case X86::BI__builtin_ia32_vpermilps256:
3624   case X86::BI__builtin_ia32_vpermilpd512:
3625   case X86::BI__builtin_ia32_vpermilps512:
3626   case X86::BI__builtin_ia32_pshufd:
3627   case X86::BI__builtin_ia32_pshufd256:
3628   case X86::BI__builtin_ia32_pshufd512:
3629   case X86::BI__builtin_ia32_pshufhw:
3630   case X86::BI__builtin_ia32_pshufhw256:
3631   case X86::BI__builtin_ia32_pshufhw512:
3632   case X86::BI__builtin_ia32_pshuflw:
3633   case X86::BI__builtin_ia32_pshuflw256:
3634   case X86::BI__builtin_ia32_pshuflw512:
3635   case X86::BI__builtin_ia32_vcvtps2ph:
3636   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3637   case X86::BI__builtin_ia32_vcvtps2ph256:
3638   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3639   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3640   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3641   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3642   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3643   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3644   case X86::BI__builtin_ia32_rndscaleps_mask:
3645   case X86::BI__builtin_ia32_rndscalepd_mask:
3646   case X86::BI__builtin_ia32_reducepd128_mask:
3647   case X86::BI__builtin_ia32_reducepd256_mask:
3648   case X86::BI__builtin_ia32_reducepd512_mask:
3649   case X86::BI__builtin_ia32_reduceps128_mask:
3650   case X86::BI__builtin_ia32_reduceps256_mask:
3651   case X86::BI__builtin_ia32_reduceps512_mask:
3652   case X86::BI__builtin_ia32_prold512:
3653   case X86::BI__builtin_ia32_prolq512:
3654   case X86::BI__builtin_ia32_prold128:
3655   case X86::BI__builtin_ia32_prold256:
3656   case X86::BI__builtin_ia32_prolq128:
3657   case X86::BI__builtin_ia32_prolq256:
3658   case X86::BI__builtin_ia32_prord512:
3659   case X86::BI__builtin_ia32_prorq512:
3660   case X86::BI__builtin_ia32_prord128:
3661   case X86::BI__builtin_ia32_prord256:
3662   case X86::BI__builtin_ia32_prorq128:
3663   case X86::BI__builtin_ia32_prorq256:
3664   case X86::BI__builtin_ia32_fpclasspd128_mask:
3665   case X86::BI__builtin_ia32_fpclasspd256_mask:
3666   case X86::BI__builtin_ia32_fpclassps128_mask:
3667   case X86::BI__builtin_ia32_fpclassps256_mask:
3668   case X86::BI__builtin_ia32_fpclassps512_mask:
3669   case X86::BI__builtin_ia32_fpclasspd512_mask:
3670   case X86::BI__builtin_ia32_fpclasssd_mask:
3671   case X86::BI__builtin_ia32_fpclassss_mask:
3672   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3673   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3674   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3675   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3676   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3677   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3678   case X86::BI__builtin_ia32_kshiftliqi:
3679   case X86::BI__builtin_ia32_kshiftlihi:
3680   case X86::BI__builtin_ia32_kshiftlisi:
3681   case X86::BI__builtin_ia32_kshiftlidi:
3682   case X86::BI__builtin_ia32_kshiftriqi:
3683   case X86::BI__builtin_ia32_kshiftrihi:
3684   case X86::BI__builtin_ia32_kshiftrisi:
3685   case X86::BI__builtin_ia32_kshiftridi:
3686     i = 1; l = 0; u = 255;
3687     break;
3688   case X86::BI__builtin_ia32_vperm2f128_pd256:
3689   case X86::BI__builtin_ia32_vperm2f128_ps256:
3690   case X86::BI__builtin_ia32_vperm2f128_si256:
3691   case X86::BI__builtin_ia32_permti256:
3692   case X86::BI__builtin_ia32_pblendw128:
3693   case X86::BI__builtin_ia32_pblendw256:
3694   case X86::BI__builtin_ia32_blendps256:
3695   case X86::BI__builtin_ia32_pblendd256:
3696   case X86::BI__builtin_ia32_palignr128:
3697   case X86::BI__builtin_ia32_palignr256:
3698   case X86::BI__builtin_ia32_palignr512:
3699   case X86::BI__builtin_ia32_alignq512:
3700   case X86::BI__builtin_ia32_alignd512:
3701   case X86::BI__builtin_ia32_alignd128:
3702   case X86::BI__builtin_ia32_alignd256:
3703   case X86::BI__builtin_ia32_alignq128:
3704   case X86::BI__builtin_ia32_alignq256:
3705   case X86::BI__builtin_ia32_vcomisd:
3706   case X86::BI__builtin_ia32_vcomiss:
3707   case X86::BI__builtin_ia32_shuf_f32x4:
3708   case X86::BI__builtin_ia32_shuf_f64x2:
3709   case X86::BI__builtin_ia32_shuf_i32x4:
3710   case X86::BI__builtin_ia32_shuf_i64x2:
3711   case X86::BI__builtin_ia32_shufpd512:
3712   case X86::BI__builtin_ia32_shufps:
3713   case X86::BI__builtin_ia32_shufps256:
3714   case X86::BI__builtin_ia32_shufps512:
3715   case X86::BI__builtin_ia32_dbpsadbw128:
3716   case X86::BI__builtin_ia32_dbpsadbw256:
3717   case X86::BI__builtin_ia32_dbpsadbw512:
3718   case X86::BI__builtin_ia32_vpshldd128:
3719   case X86::BI__builtin_ia32_vpshldd256:
3720   case X86::BI__builtin_ia32_vpshldd512:
3721   case X86::BI__builtin_ia32_vpshldq128:
3722   case X86::BI__builtin_ia32_vpshldq256:
3723   case X86::BI__builtin_ia32_vpshldq512:
3724   case X86::BI__builtin_ia32_vpshldw128:
3725   case X86::BI__builtin_ia32_vpshldw256:
3726   case X86::BI__builtin_ia32_vpshldw512:
3727   case X86::BI__builtin_ia32_vpshrdd128:
3728   case X86::BI__builtin_ia32_vpshrdd256:
3729   case X86::BI__builtin_ia32_vpshrdd512:
3730   case X86::BI__builtin_ia32_vpshrdq128:
3731   case X86::BI__builtin_ia32_vpshrdq256:
3732   case X86::BI__builtin_ia32_vpshrdq512:
3733   case X86::BI__builtin_ia32_vpshrdw128:
3734   case X86::BI__builtin_ia32_vpshrdw256:
3735   case X86::BI__builtin_ia32_vpshrdw512:
3736     i = 2; l = 0; u = 255;
3737     break;
3738   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3739   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3740   case X86::BI__builtin_ia32_fixupimmps512_mask:
3741   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3742   case X86::BI__builtin_ia32_fixupimmsd_mask:
3743   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3744   case X86::BI__builtin_ia32_fixupimmss_mask:
3745   case X86::BI__builtin_ia32_fixupimmss_maskz:
3746   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3747   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3748   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3749   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3750   case X86::BI__builtin_ia32_fixupimmps128_mask:
3751   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3752   case X86::BI__builtin_ia32_fixupimmps256_mask:
3753   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3754   case X86::BI__builtin_ia32_pternlogd512_mask:
3755   case X86::BI__builtin_ia32_pternlogd512_maskz:
3756   case X86::BI__builtin_ia32_pternlogq512_mask:
3757   case X86::BI__builtin_ia32_pternlogq512_maskz:
3758   case X86::BI__builtin_ia32_pternlogd128_mask:
3759   case X86::BI__builtin_ia32_pternlogd128_maskz:
3760   case X86::BI__builtin_ia32_pternlogd256_mask:
3761   case X86::BI__builtin_ia32_pternlogd256_maskz:
3762   case X86::BI__builtin_ia32_pternlogq128_mask:
3763   case X86::BI__builtin_ia32_pternlogq128_maskz:
3764   case X86::BI__builtin_ia32_pternlogq256_mask:
3765   case X86::BI__builtin_ia32_pternlogq256_maskz:
3766     i = 3; l = 0; u = 255;
3767     break;
3768   case X86::BI__builtin_ia32_gatherpfdpd:
3769   case X86::BI__builtin_ia32_gatherpfdps:
3770   case X86::BI__builtin_ia32_gatherpfqpd:
3771   case X86::BI__builtin_ia32_gatherpfqps:
3772   case X86::BI__builtin_ia32_scatterpfdpd:
3773   case X86::BI__builtin_ia32_scatterpfdps:
3774   case X86::BI__builtin_ia32_scatterpfqpd:
3775   case X86::BI__builtin_ia32_scatterpfqps:
3776     i = 4; l = 2; u = 3;
3777     break;
3778   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3779   case X86::BI__builtin_ia32_rndscaless_round_mask:
3780     i = 4; l = 0; u = 255;
3781     break;
3782   }
3783 
3784   // Note that we don't force a hard error on the range check here, allowing
3785   // template-generated or macro-generated dead code to potentially have out-of-
3786   // range values. These need to code generate, but don't need to necessarily
3787   // make any sense. We use a warning that defaults to an error.
3788   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3789 }
3790 
3791 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3792 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3793 /// Returns true when the format fits the function and the FormatStringInfo has
3794 /// been populated.
3795 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3796                                FormatStringInfo *FSI) {
3797   FSI->HasVAListArg = Format->getFirstArg() == 0;
3798   FSI->FormatIdx = Format->getFormatIdx() - 1;
3799   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3800 
3801   // The way the format attribute works in GCC, the implicit this argument
3802   // of member functions is counted. However, it doesn't appear in our own
3803   // lists, so decrement format_idx in that case.
3804   if (IsCXXMember) {
3805     if(FSI->FormatIdx == 0)
3806       return false;
3807     --FSI->FormatIdx;
3808     if (FSI->FirstDataArg != 0)
3809       --FSI->FirstDataArg;
3810   }
3811   return true;
3812 }
3813 
3814 /// Checks if a the given expression evaluates to null.
3815 ///
3816 /// Returns true if the value evaluates to null.
3817 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3818   // If the expression has non-null type, it doesn't evaluate to null.
3819   if (auto nullability
3820         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
3821     if (*nullability == NullabilityKind::NonNull)
3822       return false;
3823   }
3824 
3825   // As a special case, transparent unions initialized with zero are
3826   // considered null for the purposes of the nonnull attribute.
3827   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
3828     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
3829       if (const CompoundLiteralExpr *CLE =
3830           dyn_cast<CompoundLiteralExpr>(Expr))
3831         if (const InitListExpr *ILE =
3832             dyn_cast<InitListExpr>(CLE->getInitializer()))
3833           Expr = ILE->getInit(0);
3834   }
3835 
3836   bool Result;
3837   return (!Expr->isValueDependent() &&
3838           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
3839           !Result);
3840 }
3841 
3842 static void CheckNonNullArgument(Sema &S,
3843                                  const Expr *ArgExpr,
3844                                  SourceLocation CallSiteLoc) {
3845   if (CheckNonNullExpr(S, ArgExpr))
3846     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3847            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
3848 }
3849 
3850 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
3851   FormatStringInfo FSI;
3852   if ((GetFormatStringType(Format) == FST_NSString) &&
3853       getFormatStringInfo(Format, false, &FSI)) {
3854     Idx = FSI.FormatIdx;
3855     return true;
3856   }
3857   return false;
3858 }
3859 
3860 /// Diagnose use of %s directive in an NSString which is being passed
3861 /// as formatting string to formatting method.
3862 static void
3863 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
3864                                         const NamedDecl *FDecl,
3865                                         Expr **Args,
3866                                         unsigned NumArgs) {
3867   unsigned Idx = 0;
3868   bool Format = false;
3869   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
3870   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
3871     Idx = 2;
3872     Format = true;
3873   }
3874   else
3875     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3876       if (S.GetFormatNSStringIdx(I, Idx)) {
3877         Format = true;
3878         break;
3879       }
3880     }
3881   if (!Format || NumArgs <= Idx)
3882     return;
3883   const Expr *FormatExpr = Args[Idx];
3884   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
3885     FormatExpr = CSCE->getSubExpr();
3886   const StringLiteral *FormatString;
3887   if (const ObjCStringLiteral *OSL =
3888       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
3889     FormatString = OSL->getString();
3890   else
3891     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
3892   if (!FormatString)
3893     return;
3894   if (S.FormatStringHasSArg(FormatString)) {
3895     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
3896       << "%s" << 1 << 1;
3897     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
3898       << FDecl->getDeclName();
3899   }
3900 }
3901 
3902 /// Determine whether the given type has a non-null nullability annotation.
3903 static bool isNonNullType(ASTContext &ctx, QualType type) {
3904   if (auto nullability = type->getNullability(ctx))
3905     return *nullability == NullabilityKind::NonNull;
3906 
3907   return false;
3908 }
3909 
3910 static void CheckNonNullArguments(Sema &S,
3911                                   const NamedDecl *FDecl,
3912                                   const FunctionProtoType *Proto,
3913                                   ArrayRef<const Expr *> Args,
3914                                   SourceLocation CallSiteLoc) {
3915   assert((FDecl || Proto) && "Need a function declaration or prototype");
3916 
3917   // Check the attributes attached to the method/function itself.
3918   llvm::SmallBitVector NonNullArgs;
3919   if (FDecl) {
3920     // Handle the nonnull attribute on the function/method declaration itself.
3921     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3922       if (!NonNull->args_size()) {
3923         // Easy case: all pointer arguments are nonnull.
3924         for (const auto *Arg : Args)
3925           if (S.isValidPointerAttrType(Arg->getType()))
3926             CheckNonNullArgument(S, Arg, CallSiteLoc);
3927         return;
3928       }
3929 
3930       for (const ParamIdx &Idx : NonNull->args()) {
3931         unsigned IdxAST = Idx.getASTIndex();
3932         if (IdxAST >= Args.size())
3933           continue;
3934         if (NonNullArgs.empty())
3935           NonNullArgs.resize(Args.size());
3936         NonNullArgs.set(IdxAST);
3937       }
3938     }
3939   }
3940 
3941   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3942     // Handle the nonnull attribute on the parameters of the
3943     // function/method.
3944     ArrayRef<ParmVarDecl*> parms;
3945     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3946       parms = FD->parameters();
3947     else
3948       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3949 
3950     unsigned ParamIndex = 0;
3951     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3952          I != E; ++I, ++ParamIndex) {
3953       const ParmVarDecl *PVD = *I;
3954       if (PVD->hasAttr<NonNullAttr>() ||
3955           isNonNullType(S.Context, PVD->getType())) {
3956         if (NonNullArgs.empty())
3957           NonNullArgs.resize(Args.size());
3958 
3959         NonNullArgs.set(ParamIndex);
3960       }
3961     }
3962   } else {
3963     // If we have a non-function, non-method declaration but no
3964     // function prototype, try to dig out the function prototype.
3965     if (!Proto) {
3966       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3967         QualType type = VD->getType().getNonReferenceType();
3968         if (auto pointerType = type->getAs<PointerType>())
3969           type = pointerType->getPointeeType();
3970         else if (auto blockType = type->getAs<BlockPointerType>())
3971           type = blockType->getPointeeType();
3972         // FIXME: data member pointers?
3973 
3974         // Dig out the function prototype, if there is one.
3975         Proto = type->getAs<FunctionProtoType>();
3976       }
3977     }
3978 
3979     // Fill in non-null argument information from the nullability
3980     // information on the parameter types (if we have them).
3981     if (Proto) {
3982       unsigned Index = 0;
3983       for (auto paramType : Proto->getParamTypes()) {
3984         if (isNonNullType(S.Context, paramType)) {
3985           if (NonNullArgs.empty())
3986             NonNullArgs.resize(Args.size());
3987 
3988           NonNullArgs.set(Index);
3989         }
3990 
3991         ++Index;
3992       }
3993     }
3994   }
3995 
3996   // Check for non-null arguments.
3997   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3998        ArgIndex != ArgIndexEnd; ++ArgIndex) {
3999     if (NonNullArgs[ArgIndex])
4000       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4001   }
4002 }
4003 
4004 /// Handles the checks for format strings, non-POD arguments to vararg
4005 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4006 /// attributes.
4007 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4008                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4009                      bool IsMemberFunction, SourceLocation Loc,
4010                      SourceRange Range, VariadicCallType CallType) {
4011   // FIXME: We should check as much as we can in the template definition.
4012   if (CurContext->isDependentContext())
4013     return;
4014 
4015   // Printf and scanf checking.
4016   llvm::SmallBitVector CheckedVarArgs;
4017   if (FDecl) {
4018     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4019       // Only create vector if there are format attributes.
4020       CheckedVarArgs.resize(Args.size());
4021 
4022       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4023                            CheckedVarArgs);
4024     }
4025   }
4026 
4027   // Refuse POD arguments that weren't caught by the format string
4028   // checks above.
4029   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4030   if (CallType != VariadicDoesNotApply &&
4031       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4032     unsigned NumParams = Proto ? Proto->getNumParams()
4033                        : FDecl && isa<FunctionDecl>(FDecl)
4034                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4035                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4036                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4037                        : 0;
4038 
4039     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4040       // Args[ArgIdx] can be null in malformed code.
4041       if (const Expr *Arg = Args[ArgIdx]) {
4042         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4043           checkVariadicArgument(Arg, CallType);
4044       }
4045     }
4046   }
4047 
4048   if (FDecl || Proto) {
4049     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4050 
4051     // Type safety checking.
4052     if (FDecl) {
4053       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4054         CheckArgumentWithTypeTag(I, Args, Loc);
4055     }
4056   }
4057 
4058   if (FD)
4059     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4060 }
4061 
4062 /// CheckConstructorCall - Check a constructor call for correctness and safety
4063 /// properties not enforced by the C type system.
4064 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4065                                 ArrayRef<const Expr *> Args,
4066                                 const FunctionProtoType *Proto,
4067                                 SourceLocation Loc) {
4068   VariadicCallType CallType =
4069     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4070   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4071             Loc, SourceRange(), CallType);
4072 }
4073 
4074 /// CheckFunctionCall - Check a direct function call for various correctness
4075 /// and safety properties not strictly enforced by the C type system.
4076 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4077                              const FunctionProtoType *Proto) {
4078   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4079                               isa<CXXMethodDecl>(FDecl);
4080   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4081                           IsMemberOperatorCall;
4082   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4083                                                   TheCall->getCallee());
4084   Expr** Args = TheCall->getArgs();
4085   unsigned NumArgs = TheCall->getNumArgs();
4086 
4087   Expr *ImplicitThis = nullptr;
4088   if (IsMemberOperatorCall) {
4089     // If this is a call to a member operator, hide the first argument
4090     // from checkCall.
4091     // FIXME: Our choice of AST representation here is less than ideal.
4092     ImplicitThis = Args[0];
4093     ++Args;
4094     --NumArgs;
4095   } else if (IsMemberFunction)
4096     ImplicitThis =
4097         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4098 
4099   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4100             IsMemberFunction, TheCall->getRParenLoc(),
4101             TheCall->getCallee()->getSourceRange(), CallType);
4102 
4103   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4104   // None of the checks below are needed for functions that don't have
4105   // simple names (e.g., C++ conversion functions).
4106   if (!FnInfo)
4107     return false;
4108 
4109   CheckAbsoluteValueFunction(TheCall, FDecl);
4110   CheckMaxUnsignedZero(TheCall, FDecl);
4111 
4112   if (getLangOpts().ObjC1)
4113     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4114 
4115   unsigned CMId = FDecl->getMemoryFunctionKind();
4116   if (CMId == 0)
4117     return false;
4118 
4119   // Handle memory setting and copying functions.
4120   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4121     CheckStrlcpycatArguments(TheCall, FnInfo);
4122   else if (CMId == Builtin::BIstrncat)
4123     CheckStrncatArguments(TheCall, FnInfo);
4124   else
4125     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4126 
4127   return false;
4128 }
4129 
4130 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4131                                ArrayRef<const Expr *> Args) {
4132   VariadicCallType CallType =
4133       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4134 
4135   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4136             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4137             CallType);
4138 
4139   return false;
4140 }
4141 
4142 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4143                             const FunctionProtoType *Proto) {
4144   QualType Ty;
4145   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4146     Ty = V->getType().getNonReferenceType();
4147   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4148     Ty = F->getType().getNonReferenceType();
4149   else
4150     return false;
4151 
4152   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4153       !Ty->isFunctionProtoType())
4154     return false;
4155 
4156   VariadicCallType CallType;
4157   if (!Proto || !Proto->isVariadic()) {
4158     CallType = VariadicDoesNotApply;
4159   } else if (Ty->isBlockPointerType()) {
4160     CallType = VariadicBlock;
4161   } else { // Ty->isFunctionPointerType()
4162     CallType = VariadicFunction;
4163   }
4164 
4165   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4166             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4167             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4168             TheCall->getCallee()->getSourceRange(), CallType);
4169 
4170   return false;
4171 }
4172 
4173 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4174 /// such as function pointers returned from functions.
4175 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4176   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4177                                                   TheCall->getCallee());
4178   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4179             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4180             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4181             TheCall->getCallee()->getSourceRange(), CallType);
4182 
4183   return false;
4184 }
4185 
4186 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4187   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4188     return false;
4189 
4190   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4191   switch (Op) {
4192   case AtomicExpr::AO__c11_atomic_init:
4193   case AtomicExpr::AO__opencl_atomic_init:
4194     llvm_unreachable("There is no ordering argument for an init");
4195 
4196   case AtomicExpr::AO__c11_atomic_load:
4197   case AtomicExpr::AO__opencl_atomic_load:
4198   case AtomicExpr::AO__atomic_load_n:
4199   case AtomicExpr::AO__atomic_load:
4200     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4201            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4202 
4203   case AtomicExpr::AO__c11_atomic_store:
4204   case AtomicExpr::AO__opencl_atomic_store:
4205   case AtomicExpr::AO__atomic_store:
4206   case AtomicExpr::AO__atomic_store_n:
4207     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4208            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4209            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4210 
4211   default:
4212     return true;
4213   }
4214 }
4215 
4216 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4217                                          AtomicExpr::AtomicOp Op) {
4218   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4219   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4220 
4221   // All the non-OpenCL operations take one of the following forms.
4222   // The OpenCL operations take the __c11 forms with one extra argument for
4223   // synchronization scope.
4224   enum {
4225     // C    __c11_atomic_init(A *, C)
4226     Init,
4227 
4228     // C    __c11_atomic_load(A *, int)
4229     Load,
4230 
4231     // void __atomic_load(A *, CP, int)
4232     LoadCopy,
4233 
4234     // void __atomic_store(A *, CP, int)
4235     Copy,
4236 
4237     // C    __c11_atomic_add(A *, M, int)
4238     Arithmetic,
4239 
4240     // C    __atomic_exchange_n(A *, CP, int)
4241     Xchg,
4242 
4243     // void __atomic_exchange(A *, C *, CP, int)
4244     GNUXchg,
4245 
4246     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4247     C11CmpXchg,
4248 
4249     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4250     GNUCmpXchg
4251   } Form = Init;
4252 
4253   const unsigned NumForm = GNUCmpXchg + 1;
4254   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4255   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4256   // where:
4257   //   C is an appropriate type,
4258   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4259   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4260   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4261   //   the int parameters are for orderings.
4262 
4263   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4264       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4265       "need to update code for modified forms");
4266   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4267                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4268                         AtomicExpr::AO__atomic_load,
4269                 "need to update code for modified C11 atomics");
4270   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4271                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4272   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4273                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4274                IsOpenCL;
4275   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4276              Op == AtomicExpr::AO__atomic_store_n ||
4277              Op == AtomicExpr::AO__atomic_exchange_n ||
4278              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4279   bool IsAddSub = false;
4280   bool IsMinMax = false;
4281 
4282   switch (Op) {
4283   case AtomicExpr::AO__c11_atomic_init:
4284   case AtomicExpr::AO__opencl_atomic_init:
4285     Form = Init;
4286     break;
4287 
4288   case AtomicExpr::AO__c11_atomic_load:
4289   case AtomicExpr::AO__opencl_atomic_load:
4290   case AtomicExpr::AO__atomic_load_n:
4291     Form = Load;
4292     break;
4293 
4294   case AtomicExpr::AO__atomic_load:
4295     Form = LoadCopy;
4296     break;
4297 
4298   case AtomicExpr::AO__c11_atomic_store:
4299   case AtomicExpr::AO__opencl_atomic_store:
4300   case AtomicExpr::AO__atomic_store:
4301   case AtomicExpr::AO__atomic_store_n:
4302     Form = Copy;
4303     break;
4304 
4305   case AtomicExpr::AO__c11_atomic_fetch_add:
4306   case AtomicExpr::AO__c11_atomic_fetch_sub:
4307   case AtomicExpr::AO__opencl_atomic_fetch_add:
4308   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4309   case AtomicExpr::AO__opencl_atomic_fetch_min:
4310   case AtomicExpr::AO__opencl_atomic_fetch_max:
4311   case AtomicExpr::AO__atomic_fetch_add:
4312   case AtomicExpr::AO__atomic_fetch_sub:
4313   case AtomicExpr::AO__atomic_add_fetch:
4314   case AtomicExpr::AO__atomic_sub_fetch:
4315     IsAddSub = true;
4316     LLVM_FALLTHROUGH;
4317   case AtomicExpr::AO__c11_atomic_fetch_and:
4318   case AtomicExpr::AO__c11_atomic_fetch_or:
4319   case AtomicExpr::AO__c11_atomic_fetch_xor:
4320   case AtomicExpr::AO__opencl_atomic_fetch_and:
4321   case AtomicExpr::AO__opencl_atomic_fetch_or:
4322   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4323   case AtomicExpr::AO__atomic_fetch_and:
4324   case AtomicExpr::AO__atomic_fetch_or:
4325   case AtomicExpr::AO__atomic_fetch_xor:
4326   case AtomicExpr::AO__atomic_fetch_nand:
4327   case AtomicExpr::AO__atomic_and_fetch:
4328   case AtomicExpr::AO__atomic_or_fetch:
4329   case AtomicExpr::AO__atomic_xor_fetch:
4330   case AtomicExpr::AO__atomic_nand_fetch:
4331     Form = Arithmetic;
4332     break;
4333 
4334   case AtomicExpr::AO__atomic_fetch_min:
4335   case AtomicExpr::AO__atomic_fetch_max:
4336     IsMinMax = true;
4337     Form = Arithmetic;
4338     break;
4339 
4340   case AtomicExpr::AO__c11_atomic_exchange:
4341   case AtomicExpr::AO__opencl_atomic_exchange:
4342   case AtomicExpr::AO__atomic_exchange_n:
4343     Form = Xchg;
4344     break;
4345 
4346   case AtomicExpr::AO__atomic_exchange:
4347     Form = GNUXchg;
4348     break;
4349 
4350   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4351   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4352   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4353   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4354     Form = C11CmpXchg;
4355     break;
4356 
4357   case AtomicExpr::AO__atomic_compare_exchange:
4358   case AtomicExpr::AO__atomic_compare_exchange_n:
4359     Form = GNUCmpXchg;
4360     break;
4361   }
4362 
4363   unsigned AdjustedNumArgs = NumArgs[Form];
4364   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4365     ++AdjustedNumArgs;
4366   // Check we have the right number of arguments.
4367   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4368     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4369         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4370         << TheCall->getCallee()->getSourceRange();
4371     return ExprError();
4372   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4373     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4374          diag::err_typecheck_call_too_many_args)
4375         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4376         << TheCall->getCallee()->getSourceRange();
4377     return ExprError();
4378   }
4379 
4380   // Inspect the first argument of the atomic operation.
4381   Expr *Ptr = TheCall->getArg(0);
4382   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4383   if (ConvertedPtr.isInvalid())
4384     return ExprError();
4385 
4386   Ptr = ConvertedPtr.get();
4387   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4388   if (!pointerType) {
4389     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4390         << Ptr->getType() << Ptr->getSourceRange();
4391     return ExprError();
4392   }
4393 
4394   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4395   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4396   QualType ValType = AtomTy; // 'C'
4397   if (IsC11) {
4398     if (!AtomTy->isAtomicType()) {
4399       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4400           << Ptr->getType() << Ptr->getSourceRange();
4401       return ExprError();
4402     }
4403     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4404         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4405       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4406           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4407           << Ptr->getSourceRange();
4408       return ExprError();
4409     }
4410     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4411   } else if (Form != Load && Form != LoadCopy) {
4412     if (ValType.isConstQualified()) {
4413       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4414           << Ptr->getType() << Ptr->getSourceRange();
4415       return ExprError();
4416     }
4417   }
4418 
4419   // For an arithmetic operation, the implied arithmetic must be well-formed.
4420   if (Form == Arithmetic) {
4421     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4422     if (IsAddSub && !ValType->isIntegerType()
4423         && !ValType->isPointerType()) {
4424       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4425           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4426       return ExprError();
4427     }
4428     if (IsMinMax) {
4429       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4430       if (!BT || (BT->getKind() != BuiltinType::Int &&
4431                   BT->getKind() != BuiltinType::UInt)) {
4432         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4433         return ExprError();
4434       }
4435     }
4436     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4437       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4438           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4439       return ExprError();
4440     }
4441     if (IsC11 && ValType->isPointerType() &&
4442         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4443                             diag::err_incomplete_type)) {
4444       return ExprError();
4445     }
4446   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4447     // For __atomic_*_n operations, the value type must be a scalar integral or
4448     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4449     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4450         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4451     return ExprError();
4452   }
4453 
4454   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4455       !AtomTy->isScalarType()) {
4456     // For GNU atomics, require a trivially-copyable type. This is not part of
4457     // the GNU atomics specification, but we enforce it for sanity.
4458     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4459         << Ptr->getType() << Ptr->getSourceRange();
4460     return ExprError();
4461   }
4462 
4463   switch (ValType.getObjCLifetime()) {
4464   case Qualifiers::OCL_None:
4465   case Qualifiers::OCL_ExplicitNone:
4466     // okay
4467     break;
4468 
4469   case Qualifiers::OCL_Weak:
4470   case Qualifiers::OCL_Strong:
4471   case Qualifiers::OCL_Autoreleasing:
4472     // FIXME: Can this happen? By this point, ValType should be known
4473     // to be trivially copyable.
4474     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4475         << ValType << Ptr->getSourceRange();
4476     return ExprError();
4477   }
4478 
4479   // All atomic operations have an overload which takes a pointer to a volatile
4480   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4481   // into the result or the other operands. Similarly atomic_load takes a
4482   // pointer to a const 'A'.
4483   ValType.removeLocalVolatile();
4484   ValType.removeLocalConst();
4485   QualType ResultType = ValType;
4486   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4487       Form == Init)
4488     ResultType = Context.VoidTy;
4489   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4490     ResultType = Context.BoolTy;
4491 
4492   // The type of a parameter passed 'by value'. In the GNU atomics, such
4493   // arguments are actually passed as pointers.
4494   QualType ByValType = ValType; // 'CP'
4495   bool IsPassedByAddress = false;
4496   if (!IsC11 && !IsN) {
4497     ByValType = Ptr->getType();
4498     IsPassedByAddress = true;
4499   }
4500 
4501   // The first argument's non-CV pointer type is used to deduce the type of
4502   // subsequent arguments, except for:
4503   //  - weak flag (always converted to bool)
4504   //  - memory order (always converted to int)
4505   //  - scope  (always converted to int)
4506   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4507     QualType Ty;
4508     if (i < NumVals[Form] + 1) {
4509       switch (i) {
4510       case 0:
4511         // The first argument is always a pointer. It has a fixed type.
4512         // It is always dereferenced, a nullptr is undefined.
4513         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4514         // Nothing else to do: we already know all we want about this pointer.
4515         continue;
4516       case 1:
4517         // The second argument is the non-atomic operand. For arithmetic, this
4518         // is always passed by value, and for a compare_exchange it is always
4519         // passed by address. For the rest, GNU uses by-address and C11 uses
4520         // by-value.
4521         assert(Form != Load);
4522         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4523           Ty = ValType;
4524         else if (Form == Copy || Form == Xchg) {
4525           if (IsPassedByAddress)
4526             // The value pointer is always dereferenced, a nullptr is undefined.
4527             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4528           Ty = ByValType;
4529         } else if (Form == Arithmetic)
4530           Ty = Context.getPointerDiffType();
4531         else {
4532           Expr *ValArg = TheCall->getArg(i);
4533           // The value pointer is always dereferenced, a nullptr is undefined.
4534           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4535           LangAS AS = LangAS::Default;
4536           // Keep address space of non-atomic pointer type.
4537           if (const PointerType *PtrTy =
4538                   ValArg->getType()->getAs<PointerType>()) {
4539             AS = PtrTy->getPointeeType().getAddressSpace();
4540           }
4541           Ty = Context.getPointerType(
4542               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4543         }
4544         break;
4545       case 2:
4546         // The third argument to compare_exchange / GNU exchange is the desired
4547         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4548         if (IsPassedByAddress)
4549           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4550         Ty = ByValType;
4551         break;
4552       case 3:
4553         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4554         Ty = Context.BoolTy;
4555         break;
4556       }
4557     } else {
4558       // The order(s) and scope are always converted to int.
4559       Ty = Context.IntTy;
4560     }
4561 
4562     InitializedEntity Entity =
4563         InitializedEntity::InitializeParameter(Context, Ty, false);
4564     ExprResult Arg = TheCall->getArg(i);
4565     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4566     if (Arg.isInvalid())
4567       return true;
4568     TheCall->setArg(i, Arg.get());
4569   }
4570 
4571   // Permute the arguments into a 'consistent' order.
4572   SmallVector<Expr*, 5> SubExprs;
4573   SubExprs.push_back(Ptr);
4574   switch (Form) {
4575   case Init:
4576     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4577     SubExprs.push_back(TheCall->getArg(1)); // Val1
4578     break;
4579   case Load:
4580     SubExprs.push_back(TheCall->getArg(1)); // Order
4581     break;
4582   case LoadCopy:
4583   case Copy:
4584   case Arithmetic:
4585   case Xchg:
4586     SubExprs.push_back(TheCall->getArg(2)); // Order
4587     SubExprs.push_back(TheCall->getArg(1)); // Val1
4588     break;
4589   case GNUXchg:
4590     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4591     SubExprs.push_back(TheCall->getArg(3)); // Order
4592     SubExprs.push_back(TheCall->getArg(1)); // Val1
4593     SubExprs.push_back(TheCall->getArg(2)); // Val2
4594     break;
4595   case C11CmpXchg:
4596     SubExprs.push_back(TheCall->getArg(3)); // Order
4597     SubExprs.push_back(TheCall->getArg(1)); // Val1
4598     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4599     SubExprs.push_back(TheCall->getArg(2)); // Val2
4600     break;
4601   case GNUCmpXchg:
4602     SubExprs.push_back(TheCall->getArg(4)); // Order
4603     SubExprs.push_back(TheCall->getArg(1)); // Val1
4604     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4605     SubExprs.push_back(TheCall->getArg(2)); // Val2
4606     SubExprs.push_back(TheCall->getArg(3)); // Weak
4607     break;
4608   }
4609 
4610   if (SubExprs.size() >= 2 && Form != Init) {
4611     llvm::APSInt Result(32);
4612     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4613         !isValidOrderingForOp(Result.getSExtValue(), Op))
4614       Diag(SubExprs[1]->getBeginLoc(),
4615            diag::warn_atomic_op_has_invalid_memory_order)
4616           << SubExprs[1]->getSourceRange();
4617   }
4618 
4619   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4620     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4621     llvm::APSInt Result(32);
4622     if (Scope->isIntegerConstantExpr(Result, Context) &&
4623         !ScopeModel->isValid(Result.getZExtValue())) {
4624       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4625           << Scope->getSourceRange();
4626     }
4627     SubExprs.push_back(Scope);
4628   }
4629 
4630   AtomicExpr *AE =
4631       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4632                                ResultType, Op, TheCall->getRParenLoc());
4633 
4634   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4635        Op == AtomicExpr::AO__c11_atomic_store ||
4636        Op == AtomicExpr::AO__opencl_atomic_load ||
4637        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4638       Context.AtomicUsesUnsupportedLibcall(AE))
4639     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4640         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4641              Op == AtomicExpr::AO__opencl_atomic_load)
4642                 ? 0
4643                 : 1);
4644 
4645   return AE;
4646 }
4647 
4648 /// checkBuiltinArgument - Given a call to a builtin function, perform
4649 /// normal type-checking on the given argument, updating the call in
4650 /// place.  This is useful when a builtin function requires custom
4651 /// type-checking for some of its arguments but not necessarily all of
4652 /// them.
4653 ///
4654 /// Returns true on error.
4655 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4656   FunctionDecl *Fn = E->getDirectCallee();
4657   assert(Fn && "builtin call without direct callee!");
4658 
4659   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4660   InitializedEntity Entity =
4661     InitializedEntity::InitializeParameter(S.Context, Param);
4662 
4663   ExprResult Arg = E->getArg(0);
4664   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4665   if (Arg.isInvalid())
4666     return true;
4667 
4668   E->setArg(ArgIndex, Arg.get());
4669   return false;
4670 }
4671 
4672 /// We have a call to a function like __sync_fetch_and_add, which is an
4673 /// overloaded function based on the pointer type of its first argument.
4674 /// The main ActOnCallExpr routines have already promoted the types of
4675 /// arguments because all of these calls are prototyped as void(...).
4676 ///
4677 /// This function goes through and does final semantic checking for these
4678 /// builtins, as well as generating any warnings.
4679 ExprResult
4680 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4681   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4682   Expr *Callee = TheCall->getCallee();
4683   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4684   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4685 
4686   // Ensure that we have at least one argument to do type inference from.
4687   if (TheCall->getNumArgs() < 1) {
4688     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4689         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4690     return ExprError();
4691   }
4692 
4693   // Inspect the first argument of the atomic builtin.  This should always be
4694   // a pointer type, whose element is an integral scalar or pointer type.
4695   // Because it is a pointer type, we don't have to worry about any implicit
4696   // casts here.
4697   // FIXME: We don't allow floating point scalars as input.
4698   Expr *FirstArg = TheCall->getArg(0);
4699   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4700   if (FirstArgResult.isInvalid())
4701     return ExprError();
4702   FirstArg = FirstArgResult.get();
4703   TheCall->setArg(0, FirstArg);
4704 
4705   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4706   if (!pointerType) {
4707     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4708         << FirstArg->getType() << FirstArg->getSourceRange();
4709     return ExprError();
4710   }
4711 
4712   QualType ValType = pointerType->getPointeeType();
4713   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4714       !ValType->isBlockPointerType()) {
4715     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4716         << FirstArg->getType() << FirstArg->getSourceRange();
4717     return ExprError();
4718   }
4719 
4720   if (ValType.isConstQualified()) {
4721     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4722         << FirstArg->getType() << FirstArg->getSourceRange();
4723     return ExprError();
4724   }
4725 
4726   switch (ValType.getObjCLifetime()) {
4727   case Qualifiers::OCL_None:
4728   case Qualifiers::OCL_ExplicitNone:
4729     // okay
4730     break;
4731 
4732   case Qualifiers::OCL_Weak:
4733   case Qualifiers::OCL_Strong:
4734   case Qualifiers::OCL_Autoreleasing:
4735     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4736         << ValType << FirstArg->getSourceRange();
4737     return ExprError();
4738   }
4739 
4740   // Strip any qualifiers off ValType.
4741   ValType = ValType.getUnqualifiedType();
4742 
4743   // The majority of builtins return a value, but a few have special return
4744   // types, so allow them to override appropriately below.
4745   QualType ResultType = ValType;
4746 
4747   // We need to figure out which concrete builtin this maps onto.  For example,
4748   // __sync_fetch_and_add with a 2 byte object turns into
4749   // __sync_fetch_and_add_2.
4750 #define BUILTIN_ROW(x) \
4751   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4752     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4753 
4754   static const unsigned BuiltinIndices[][5] = {
4755     BUILTIN_ROW(__sync_fetch_and_add),
4756     BUILTIN_ROW(__sync_fetch_and_sub),
4757     BUILTIN_ROW(__sync_fetch_and_or),
4758     BUILTIN_ROW(__sync_fetch_and_and),
4759     BUILTIN_ROW(__sync_fetch_and_xor),
4760     BUILTIN_ROW(__sync_fetch_and_nand),
4761 
4762     BUILTIN_ROW(__sync_add_and_fetch),
4763     BUILTIN_ROW(__sync_sub_and_fetch),
4764     BUILTIN_ROW(__sync_and_and_fetch),
4765     BUILTIN_ROW(__sync_or_and_fetch),
4766     BUILTIN_ROW(__sync_xor_and_fetch),
4767     BUILTIN_ROW(__sync_nand_and_fetch),
4768 
4769     BUILTIN_ROW(__sync_val_compare_and_swap),
4770     BUILTIN_ROW(__sync_bool_compare_and_swap),
4771     BUILTIN_ROW(__sync_lock_test_and_set),
4772     BUILTIN_ROW(__sync_lock_release),
4773     BUILTIN_ROW(__sync_swap)
4774   };
4775 #undef BUILTIN_ROW
4776 
4777   // Determine the index of the size.
4778   unsigned SizeIndex;
4779   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4780   case 1: SizeIndex = 0; break;
4781   case 2: SizeIndex = 1; break;
4782   case 4: SizeIndex = 2; break;
4783   case 8: SizeIndex = 3; break;
4784   case 16: SizeIndex = 4; break;
4785   default:
4786     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4787         << FirstArg->getType() << FirstArg->getSourceRange();
4788     return ExprError();
4789   }
4790 
4791   // Each of these builtins has one pointer argument, followed by some number of
4792   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4793   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4794   // as the number of fixed args.
4795   unsigned BuiltinID = FDecl->getBuiltinID();
4796   unsigned BuiltinIndex, NumFixed = 1;
4797   bool WarnAboutSemanticsChange = false;
4798   switch (BuiltinID) {
4799   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4800   case Builtin::BI__sync_fetch_and_add:
4801   case Builtin::BI__sync_fetch_and_add_1:
4802   case Builtin::BI__sync_fetch_and_add_2:
4803   case Builtin::BI__sync_fetch_and_add_4:
4804   case Builtin::BI__sync_fetch_and_add_8:
4805   case Builtin::BI__sync_fetch_and_add_16:
4806     BuiltinIndex = 0;
4807     break;
4808 
4809   case Builtin::BI__sync_fetch_and_sub:
4810   case Builtin::BI__sync_fetch_and_sub_1:
4811   case Builtin::BI__sync_fetch_and_sub_2:
4812   case Builtin::BI__sync_fetch_and_sub_4:
4813   case Builtin::BI__sync_fetch_and_sub_8:
4814   case Builtin::BI__sync_fetch_and_sub_16:
4815     BuiltinIndex = 1;
4816     break;
4817 
4818   case Builtin::BI__sync_fetch_and_or:
4819   case Builtin::BI__sync_fetch_and_or_1:
4820   case Builtin::BI__sync_fetch_and_or_2:
4821   case Builtin::BI__sync_fetch_and_or_4:
4822   case Builtin::BI__sync_fetch_and_or_8:
4823   case Builtin::BI__sync_fetch_and_or_16:
4824     BuiltinIndex = 2;
4825     break;
4826 
4827   case Builtin::BI__sync_fetch_and_and:
4828   case Builtin::BI__sync_fetch_and_and_1:
4829   case Builtin::BI__sync_fetch_and_and_2:
4830   case Builtin::BI__sync_fetch_and_and_4:
4831   case Builtin::BI__sync_fetch_and_and_8:
4832   case Builtin::BI__sync_fetch_and_and_16:
4833     BuiltinIndex = 3;
4834     break;
4835 
4836   case Builtin::BI__sync_fetch_and_xor:
4837   case Builtin::BI__sync_fetch_and_xor_1:
4838   case Builtin::BI__sync_fetch_and_xor_2:
4839   case Builtin::BI__sync_fetch_and_xor_4:
4840   case Builtin::BI__sync_fetch_and_xor_8:
4841   case Builtin::BI__sync_fetch_and_xor_16:
4842     BuiltinIndex = 4;
4843     break;
4844 
4845   case Builtin::BI__sync_fetch_and_nand:
4846   case Builtin::BI__sync_fetch_and_nand_1:
4847   case Builtin::BI__sync_fetch_and_nand_2:
4848   case Builtin::BI__sync_fetch_and_nand_4:
4849   case Builtin::BI__sync_fetch_and_nand_8:
4850   case Builtin::BI__sync_fetch_and_nand_16:
4851     BuiltinIndex = 5;
4852     WarnAboutSemanticsChange = true;
4853     break;
4854 
4855   case Builtin::BI__sync_add_and_fetch:
4856   case Builtin::BI__sync_add_and_fetch_1:
4857   case Builtin::BI__sync_add_and_fetch_2:
4858   case Builtin::BI__sync_add_and_fetch_4:
4859   case Builtin::BI__sync_add_and_fetch_8:
4860   case Builtin::BI__sync_add_and_fetch_16:
4861     BuiltinIndex = 6;
4862     break;
4863 
4864   case Builtin::BI__sync_sub_and_fetch:
4865   case Builtin::BI__sync_sub_and_fetch_1:
4866   case Builtin::BI__sync_sub_and_fetch_2:
4867   case Builtin::BI__sync_sub_and_fetch_4:
4868   case Builtin::BI__sync_sub_and_fetch_8:
4869   case Builtin::BI__sync_sub_and_fetch_16:
4870     BuiltinIndex = 7;
4871     break;
4872 
4873   case Builtin::BI__sync_and_and_fetch:
4874   case Builtin::BI__sync_and_and_fetch_1:
4875   case Builtin::BI__sync_and_and_fetch_2:
4876   case Builtin::BI__sync_and_and_fetch_4:
4877   case Builtin::BI__sync_and_and_fetch_8:
4878   case Builtin::BI__sync_and_and_fetch_16:
4879     BuiltinIndex = 8;
4880     break;
4881 
4882   case Builtin::BI__sync_or_and_fetch:
4883   case Builtin::BI__sync_or_and_fetch_1:
4884   case Builtin::BI__sync_or_and_fetch_2:
4885   case Builtin::BI__sync_or_and_fetch_4:
4886   case Builtin::BI__sync_or_and_fetch_8:
4887   case Builtin::BI__sync_or_and_fetch_16:
4888     BuiltinIndex = 9;
4889     break;
4890 
4891   case Builtin::BI__sync_xor_and_fetch:
4892   case Builtin::BI__sync_xor_and_fetch_1:
4893   case Builtin::BI__sync_xor_and_fetch_2:
4894   case Builtin::BI__sync_xor_and_fetch_4:
4895   case Builtin::BI__sync_xor_and_fetch_8:
4896   case Builtin::BI__sync_xor_and_fetch_16:
4897     BuiltinIndex = 10;
4898     break;
4899 
4900   case Builtin::BI__sync_nand_and_fetch:
4901   case Builtin::BI__sync_nand_and_fetch_1:
4902   case Builtin::BI__sync_nand_and_fetch_2:
4903   case Builtin::BI__sync_nand_and_fetch_4:
4904   case Builtin::BI__sync_nand_and_fetch_8:
4905   case Builtin::BI__sync_nand_and_fetch_16:
4906     BuiltinIndex = 11;
4907     WarnAboutSemanticsChange = true;
4908     break;
4909 
4910   case Builtin::BI__sync_val_compare_and_swap:
4911   case Builtin::BI__sync_val_compare_and_swap_1:
4912   case Builtin::BI__sync_val_compare_and_swap_2:
4913   case Builtin::BI__sync_val_compare_and_swap_4:
4914   case Builtin::BI__sync_val_compare_and_swap_8:
4915   case Builtin::BI__sync_val_compare_and_swap_16:
4916     BuiltinIndex = 12;
4917     NumFixed = 2;
4918     break;
4919 
4920   case Builtin::BI__sync_bool_compare_and_swap:
4921   case Builtin::BI__sync_bool_compare_and_swap_1:
4922   case Builtin::BI__sync_bool_compare_and_swap_2:
4923   case Builtin::BI__sync_bool_compare_and_swap_4:
4924   case Builtin::BI__sync_bool_compare_and_swap_8:
4925   case Builtin::BI__sync_bool_compare_and_swap_16:
4926     BuiltinIndex = 13;
4927     NumFixed = 2;
4928     ResultType = Context.BoolTy;
4929     break;
4930 
4931   case Builtin::BI__sync_lock_test_and_set:
4932   case Builtin::BI__sync_lock_test_and_set_1:
4933   case Builtin::BI__sync_lock_test_and_set_2:
4934   case Builtin::BI__sync_lock_test_and_set_4:
4935   case Builtin::BI__sync_lock_test_and_set_8:
4936   case Builtin::BI__sync_lock_test_and_set_16:
4937     BuiltinIndex = 14;
4938     break;
4939 
4940   case Builtin::BI__sync_lock_release:
4941   case Builtin::BI__sync_lock_release_1:
4942   case Builtin::BI__sync_lock_release_2:
4943   case Builtin::BI__sync_lock_release_4:
4944   case Builtin::BI__sync_lock_release_8:
4945   case Builtin::BI__sync_lock_release_16:
4946     BuiltinIndex = 15;
4947     NumFixed = 0;
4948     ResultType = Context.VoidTy;
4949     break;
4950 
4951   case Builtin::BI__sync_swap:
4952   case Builtin::BI__sync_swap_1:
4953   case Builtin::BI__sync_swap_2:
4954   case Builtin::BI__sync_swap_4:
4955   case Builtin::BI__sync_swap_8:
4956   case Builtin::BI__sync_swap_16:
4957     BuiltinIndex = 16;
4958     break;
4959   }
4960 
4961   // Now that we know how many fixed arguments we expect, first check that we
4962   // have at least that many.
4963   if (TheCall->getNumArgs() < 1+NumFixed) {
4964     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4965         << 0 << 1 + NumFixed << TheCall->getNumArgs()
4966         << Callee->getSourceRange();
4967     return ExprError();
4968   }
4969 
4970   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
4971       << Callee->getSourceRange();
4972 
4973   if (WarnAboutSemanticsChange) {
4974     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
4975         << Callee->getSourceRange();
4976   }
4977 
4978   // Get the decl for the concrete builtin from this, we can tell what the
4979   // concrete integer type we should convert to is.
4980   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
4981   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
4982   FunctionDecl *NewBuiltinDecl;
4983   if (NewBuiltinID == BuiltinID)
4984     NewBuiltinDecl = FDecl;
4985   else {
4986     // Perform builtin lookup to avoid redeclaring it.
4987     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
4988     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
4989     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
4990     assert(Res.getFoundDecl());
4991     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
4992     if (!NewBuiltinDecl)
4993       return ExprError();
4994   }
4995 
4996   // The first argument --- the pointer --- has a fixed type; we
4997   // deduce the types of the rest of the arguments accordingly.  Walk
4998   // the remaining arguments, converting them to the deduced value type.
4999   for (unsigned i = 0; i != NumFixed; ++i) {
5000     ExprResult Arg = TheCall->getArg(i+1);
5001 
5002     // GCC does an implicit conversion to the pointer or integer ValType.  This
5003     // can fail in some cases (1i -> int**), check for this error case now.
5004     // Initialize the argument.
5005     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5006                                                    ValType, /*consume*/ false);
5007     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5008     if (Arg.isInvalid())
5009       return ExprError();
5010 
5011     // Okay, we have something that *can* be converted to the right type.  Check
5012     // to see if there is a potentially weird extension going on here.  This can
5013     // happen when you do an atomic operation on something like an char* and
5014     // pass in 42.  The 42 gets converted to char.  This is even more strange
5015     // for things like 45.123 -> char, etc.
5016     // FIXME: Do this check.
5017     TheCall->setArg(i+1, Arg.get());
5018   }
5019 
5020   ASTContext& Context = this->getASTContext();
5021 
5022   // Create a new DeclRefExpr to refer to the new decl.
5023   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5024       Context,
5025       DRE->getQualifierLoc(),
5026       SourceLocation(),
5027       NewBuiltinDecl,
5028       /*enclosing*/ false,
5029       DRE->getLocation(),
5030       Context.BuiltinFnTy,
5031       DRE->getValueKind());
5032 
5033   // Set the callee in the CallExpr.
5034   // FIXME: This loses syntactic information.
5035   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5036   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5037                                               CK_BuiltinFnToFnPtr);
5038   TheCall->setCallee(PromotedCall.get());
5039 
5040   // Change the result type of the call to match the original value type. This
5041   // is arbitrary, but the codegen for these builtins ins design to handle it
5042   // gracefully.
5043   TheCall->setType(ResultType);
5044 
5045   return TheCallResult;
5046 }
5047 
5048 /// SemaBuiltinNontemporalOverloaded - We have a call to
5049 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5050 /// overloaded function based on the pointer type of its last argument.
5051 ///
5052 /// This function goes through and does final semantic checking for these
5053 /// builtins.
5054 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5055   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5056   DeclRefExpr *DRE =
5057       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5058   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5059   unsigned BuiltinID = FDecl->getBuiltinID();
5060   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5061           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5062          "Unexpected nontemporal load/store builtin!");
5063   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5064   unsigned numArgs = isStore ? 2 : 1;
5065 
5066   // Ensure that we have the proper number of arguments.
5067   if (checkArgCount(*this, TheCall, numArgs))
5068     return ExprError();
5069 
5070   // Inspect the last argument of the nontemporal builtin.  This should always
5071   // be a pointer type, from which we imply the type of the memory access.
5072   // Because it is a pointer type, we don't have to worry about any implicit
5073   // casts here.
5074   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5075   ExprResult PointerArgResult =
5076       DefaultFunctionArrayLvalueConversion(PointerArg);
5077 
5078   if (PointerArgResult.isInvalid())
5079     return ExprError();
5080   PointerArg = PointerArgResult.get();
5081   TheCall->setArg(numArgs - 1, PointerArg);
5082 
5083   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5084   if (!pointerType) {
5085     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5086         << PointerArg->getType() << PointerArg->getSourceRange();
5087     return ExprError();
5088   }
5089 
5090   QualType ValType = pointerType->getPointeeType();
5091 
5092   // Strip any qualifiers off ValType.
5093   ValType = ValType.getUnqualifiedType();
5094   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5095       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5096       !ValType->isVectorType()) {
5097     Diag(DRE->getBeginLoc(),
5098          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5099         << PointerArg->getType() << PointerArg->getSourceRange();
5100     return ExprError();
5101   }
5102 
5103   if (!isStore) {
5104     TheCall->setType(ValType);
5105     return TheCallResult;
5106   }
5107 
5108   ExprResult ValArg = TheCall->getArg(0);
5109   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5110       Context, ValType, /*consume*/ false);
5111   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5112   if (ValArg.isInvalid())
5113     return ExprError();
5114 
5115   TheCall->setArg(0, ValArg.get());
5116   TheCall->setType(Context.VoidTy);
5117   return TheCallResult;
5118 }
5119 
5120 /// CheckObjCString - Checks that the argument to the builtin
5121 /// CFString constructor is correct
5122 /// Note: It might also make sense to do the UTF-16 conversion here (would
5123 /// simplify the backend).
5124 bool Sema::CheckObjCString(Expr *Arg) {
5125   Arg = Arg->IgnoreParenCasts();
5126   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5127 
5128   if (!Literal || !Literal->isAscii()) {
5129     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5130         << Arg->getSourceRange();
5131     return true;
5132   }
5133 
5134   if (Literal->containsNonAsciiOrNull()) {
5135     StringRef String = Literal->getString();
5136     unsigned NumBytes = String.size();
5137     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5138     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5139     llvm::UTF16 *ToPtr = &ToBuf[0];
5140 
5141     llvm::ConversionResult Result =
5142         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5143                                  ToPtr + NumBytes, llvm::strictConversion);
5144     // Check for conversion failure.
5145     if (Result != llvm::conversionOK)
5146       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5147           << Arg->getSourceRange();
5148   }
5149   return false;
5150 }
5151 
5152 /// CheckObjCString - Checks that the format string argument to the os_log()
5153 /// and os_trace() functions is correct, and converts it to const char *.
5154 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5155   Arg = Arg->IgnoreParenCasts();
5156   auto *Literal = dyn_cast<StringLiteral>(Arg);
5157   if (!Literal) {
5158     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5159       Literal = ObjcLiteral->getString();
5160     }
5161   }
5162 
5163   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5164     return ExprError(
5165         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5166         << Arg->getSourceRange());
5167   }
5168 
5169   ExprResult Result(Literal);
5170   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5171   InitializedEntity Entity =
5172       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5173   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5174   return Result;
5175 }
5176 
5177 /// Check that the user is calling the appropriate va_start builtin for the
5178 /// target and calling convention.
5179 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5180   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5181   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5182   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5183   bool IsWindows = TT.isOSWindows();
5184   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5185   if (IsX64 || IsAArch64) {
5186     CallingConv CC = CC_C;
5187     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5188       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5189     if (IsMSVAStart) {
5190       // Don't allow this in System V ABI functions.
5191       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5192         return S.Diag(Fn->getBeginLoc(),
5193                       diag::err_ms_va_start_used_in_sysv_function);
5194     } else {
5195       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5196       // On x64 Windows, don't allow this in System V ABI functions.
5197       // (Yes, that means there's no corresponding way to support variadic
5198       // System V ABI functions on Windows.)
5199       if ((IsWindows && CC == CC_X86_64SysV) ||
5200           (!IsWindows && CC == CC_Win64))
5201         return S.Diag(Fn->getBeginLoc(),
5202                       diag::err_va_start_used_in_wrong_abi_function)
5203                << !IsWindows;
5204     }
5205     return false;
5206   }
5207 
5208   if (IsMSVAStart)
5209     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5210   return false;
5211 }
5212 
5213 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5214                                              ParmVarDecl **LastParam = nullptr) {
5215   // Determine whether the current function, block, or obj-c method is variadic
5216   // and get its parameter list.
5217   bool IsVariadic = false;
5218   ArrayRef<ParmVarDecl *> Params;
5219   DeclContext *Caller = S.CurContext;
5220   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5221     IsVariadic = Block->isVariadic();
5222     Params = Block->parameters();
5223   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5224     IsVariadic = FD->isVariadic();
5225     Params = FD->parameters();
5226   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5227     IsVariadic = MD->isVariadic();
5228     // FIXME: This isn't correct for methods (results in bogus warning).
5229     Params = MD->parameters();
5230   } else if (isa<CapturedDecl>(Caller)) {
5231     // We don't support va_start in a CapturedDecl.
5232     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5233     return true;
5234   } else {
5235     // This must be some other declcontext that parses exprs.
5236     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5237     return true;
5238   }
5239 
5240   if (!IsVariadic) {
5241     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5242     return true;
5243   }
5244 
5245   if (LastParam)
5246     *LastParam = Params.empty() ? nullptr : Params.back();
5247 
5248   return false;
5249 }
5250 
5251 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5252 /// for validity.  Emit an error and return true on failure; return false
5253 /// on success.
5254 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5255   Expr *Fn = TheCall->getCallee();
5256 
5257   if (checkVAStartABI(*this, BuiltinID, Fn))
5258     return true;
5259 
5260   if (TheCall->getNumArgs() > 2) {
5261     Diag(TheCall->getArg(2)->getBeginLoc(),
5262          diag::err_typecheck_call_too_many_args)
5263         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5264         << Fn->getSourceRange()
5265         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5266                        (*(TheCall->arg_end() - 1))->getEndLoc());
5267     return true;
5268   }
5269 
5270   if (TheCall->getNumArgs() < 2) {
5271     return Diag(TheCall->getEndLoc(),
5272                 diag::err_typecheck_call_too_few_args_at_least)
5273            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5274   }
5275 
5276   // Type-check the first argument normally.
5277   if (checkBuiltinArgument(*this, TheCall, 0))
5278     return true;
5279 
5280   // Check that the current function is variadic, and get its last parameter.
5281   ParmVarDecl *LastParam;
5282   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5283     return true;
5284 
5285   // Verify that the second argument to the builtin is the last argument of the
5286   // current function or method.
5287   bool SecondArgIsLastNamedArgument = false;
5288   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5289 
5290   // These are valid if SecondArgIsLastNamedArgument is false after the next
5291   // block.
5292   QualType Type;
5293   SourceLocation ParamLoc;
5294   bool IsCRegister = false;
5295 
5296   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5297     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5298       SecondArgIsLastNamedArgument = PV == LastParam;
5299 
5300       Type = PV->getType();
5301       ParamLoc = PV->getLocation();
5302       IsCRegister =
5303           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5304     }
5305   }
5306 
5307   if (!SecondArgIsLastNamedArgument)
5308     Diag(TheCall->getArg(1)->getBeginLoc(),
5309          diag::warn_second_arg_of_va_start_not_last_named_param);
5310   else if (IsCRegister || Type->isReferenceType() ||
5311            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5312              // Promotable integers are UB, but enumerations need a bit of
5313              // extra checking to see what their promotable type actually is.
5314              if (!Type->isPromotableIntegerType())
5315                return false;
5316              if (!Type->isEnumeralType())
5317                return true;
5318              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5319              return !(ED &&
5320                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5321            }()) {
5322     unsigned Reason = 0;
5323     if (Type->isReferenceType())  Reason = 1;
5324     else if (IsCRegister)         Reason = 2;
5325     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5326     Diag(ParamLoc, diag::note_parameter_type) << Type;
5327   }
5328 
5329   TheCall->setType(Context.VoidTy);
5330   return false;
5331 }
5332 
5333 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5334   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5335   //                 const char *named_addr);
5336 
5337   Expr *Func = Call->getCallee();
5338 
5339   if (Call->getNumArgs() < 3)
5340     return Diag(Call->getEndLoc(),
5341                 diag::err_typecheck_call_too_few_args_at_least)
5342            << 0 /*function call*/ << 3 << Call->getNumArgs();
5343 
5344   // Type-check the first argument normally.
5345   if (checkBuiltinArgument(*this, Call, 0))
5346     return true;
5347 
5348   // Check that the current function is variadic.
5349   if (checkVAStartIsInVariadicFunction(*this, Func))
5350     return true;
5351 
5352   // __va_start on Windows does not validate the parameter qualifiers
5353 
5354   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5355   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5356 
5357   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5358   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5359 
5360   const QualType &ConstCharPtrTy =
5361       Context.getPointerType(Context.CharTy.withConst());
5362   if (!Arg1Ty->isPointerType() ||
5363       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5364     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5365         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5366         << 0                                      /* qualifier difference */
5367         << 3                                      /* parameter mismatch */
5368         << 2 << Arg1->getType() << ConstCharPtrTy;
5369 
5370   const QualType SizeTy = Context.getSizeType();
5371   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5372     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5373         << Arg2->getType() << SizeTy << 1 /* different class */
5374         << 0                              /* qualifier difference */
5375         << 3                              /* parameter mismatch */
5376         << 3 << Arg2->getType() << SizeTy;
5377 
5378   return false;
5379 }
5380 
5381 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5382 /// friends.  This is declared to take (...), so we have to check everything.
5383 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5384   if (TheCall->getNumArgs() < 2)
5385     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5386            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5387   if (TheCall->getNumArgs() > 2)
5388     return Diag(TheCall->getArg(2)->getBeginLoc(),
5389                 diag::err_typecheck_call_too_many_args)
5390            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5391            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5392                           (*(TheCall->arg_end() - 1))->getEndLoc());
5393 
5394   ExprResult OrigArg0 = TheCall->getArg(0);
5395   ExprResult OrigArg1 = TheCall->getArg(1);
5396 
5397   // Do standard promotions between the two arguments, returning their common
5398   // type.
5399   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5400   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5401     return true;
5402 
5403   // Make sure any conversions are pushed back into the call; this is
5404   // type safe since unordered compare builtins are declared as "_Bool
5405   // foo(...)".
5406   TheCall->setArg(0, OrigArg0.get());
5407   TheCall->setArg(1, OrigArg1.get());
5408 
5409   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5410     return false;
5411 
5412   // If the common type isn't a real floating type, then the arguments were
5413   // invalid for this operation.
5414   if (Res.isNull() || !Res->isRealFloatingType())
5415     return Diag(OrigArg0.get()->getBeginLoc(),
5416                 diag::err_typecheck_call_invalid_ordered_compare)
5417            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5418            << SourceRange(OrigArg0.get()->getBeginLoc(),
5419                           OrigArg1.get()->getEndLoc());
5420 
5421   return false;
5422 }
5423 
5424 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5425 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5426 /// to check everything. We expect the last argument to be a floating point
5427 /// value.
5428 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5429   if (TheCall->getNumArgs() < NumArgs)
5430     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5431            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5432   if (TheCall->getNumArgs() > NumArgs)
5433     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5434                 diag::err_typecheck_call_too_many_args)
5435            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5436            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5437                           (*(TheCall->arg_end() - 1))->getEndLoc());
5438 
5439   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5440 
5441   if (OrigArg->isTypeDependent())
5442     return false;
5443 
5444   // This operation requires a non-_Complex floating-point number.
5445   if (!OrigArg->getType()->isRealFloatingType())
5446     return Diag(OrigArg->getBeginLoc(),
5447                 diag::err_typecheck_call_invalid_unary_fp)
5448            << OrigArg->getType() << OrigArg->getSourceRange();
5449 
5450   // If this is an implicit conversion from float -> float, double, or
5451   // long double, remove it.
5452   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5453     // Only remove standard FloatCasts, leaving other casts inplace
5454     if (Cast->getCastKind() == CK_FloatingCast) {
5455       Expr *CastArg = Cast->getSubExpr();
5456       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5457         assert(
5458             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5459              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5460              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5461             "promotion from float to either float, double, or long double is "
5462             "the only expected cast here");
5463         Cast->setSubExpr(nullptr);
5464         TheCall->setArg(NumArgs-1, CastArg);
5465       }
5466     }
5467   }
5468 
5469   return false;
5470 }
5471 
5472 // Customized Sema Checking for VSX builtins that have the following signature:
5473 // vector [...] builtinName(vector [...], vector [...], const int);
5474 // Which takes the same type of vectors (any legal vector type) for the first
5475 // two arguments and takes compile time constant for the third argument.
5476 // Example builtins are :
5477 // vector double vec_xxpermdi(vector double, vector double, int);
5478 // vector short vec_xxsldwi(vector short, vector short, int);
5479 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5480   unsigned ExpectedNumArgs = 3;
5481   if (TheCall->getNumArgs() < ExpectedNumArgs)
5482     return Diag(TheCall->getEndLoc(),
5483                 diag::err_typecheck_call_too_few_args_at_least)
5484            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5485            << TheCall->getSourceRange();
5486 
5487   if (TheCall->getNumArgs() > ExpectedNumArgs)
5488     return Diag(TheCall->getEndLoc(),
5489                 diag::err_typecheck_call_too_many_args_at_most)
5490            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5491            << TheCall->getSourceRange();
5492 
5493   // Check the third argument is a compile time constant
5494   llvm::APSInt Value;
5495   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5496     return Diag(TheCall->getBeginLoc(),
5497                 diag::err_vsx_builtin_nonconstant_argument)
5498            << 3 /* argument index */ << TheCall->getDirectCallee()
5499            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5500                           TheCall->getArg(2)->getEndLoc());
5501 
5502   QualType Arg1Ty = TheCall->getArg(0)->getType();
5503   QualType Arg2Ty = TheCall->getArg(1)->getType();
5504 
5505   // Check the type of argument 1 and argument 2 are vectors.
5506   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5507   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5508       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5509     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5510            << TheCall->getDirectCallee()
5511            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5512                           TheCall->getArg(1)->getEndLoc());
5513   }
5514 
5515   // Check the first two arguments are the same type.
5516   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5517     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5518            << TheCall->getDirectCallee()
5519            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5520                           TheCall->getArg(1)->getEndLoc());
5521   }
5522 
5523   // When default clang type checking is turned off and the customized type
5524   // checking is used, the returning type of the function must be explicitly
5525   // set. Otherwise it is _Bool by default.
5526   TheCall->setType(Arg1Ty);
5527 
5528   return false;
5529 }
5530 
5531 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5532 // This is declared to take (...), so we have to check everything.
5533 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5534   if (TheCall->getNumArgs() < 2)
5535     return ExprError(Diag(TheCall->getEndLoc(),
5536                           diag::err_typecheck_call_too_few_args_at_least)
5537                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5538                      << TheCall->getSourceRange());
5539 
5540   // Determine which of the following types of shufflevector we're checking:
5541   // 1) unary, vector mask: (lhs, mask)
5542   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5543   QualType resType = TheCall->getArg(0)->getType();
5544   unsigned numElements = 0;
5545 
5546   if (!TheCall->getArg(0)->isTypeDependent() &&
5547       !TheCall->getArg(1)->isTypeDependent()) {
5548     QualType LHSType = TheCall->getArg(0)->getType();
5549     QualType RHSType = TheCall->getArg(1)->getType();
5550 
5551     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5552       return ExprError(
5553           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5554           << TheCall->getDirectCallee()
5555           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5556                          TheCall->getArg(1)->getEndLoc()));
5557 
5558     numElements = LHSType->getAs<VectorType>()->getNumElements();
5559     unsigned numResElements = TheCall->getNumArgs() - 2;
5560 
5561     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5562     // with mask.  If so, verify that RHS is an integer vector type with the
5563     // same number of elts as lhs.
5564     if (TheCall->getNumArgs() == 2) {
5565       if (!RHSType->hasIntegerRepresentation() ||
5566           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5567         return ExprError(Diag(TheCall->getBeginLoc(),
5568                               diag::err_vec_builtin_incompatible_vector)
5569                          << TheCall->getDirectCallee()
5570                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5571                                         TheCall->getArg(1)->getEndLoc()));
5572     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5573       return ExprError(Diag(TheCall->getBeginLoc(),
5574                             diag::err_vec_builtin_incompatible_vector)
5575                        << TheCall->getDirectCallee()
5576                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5577                                       TheCall->getArg(1)->getEndLoc()));
5578     } else if (numElements != numResElements) {
5579       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5580       resType = Context.getVectorType(eltType, numResElements,
5581                                       VectorType::GenericVector);
5582     }
5583   }
5584 
5585   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5586     if (TheCall->getArg(i)->isTypeDependent() ||
5587         TheCall->getArg(i)->isValueDependent())
5588       continue;
5589 
5590     llvm::APSInt Result(32);
5591     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5592       return ExprError(Diag(TheCall->getBeginLoc(),
5593                             diag::err_shufflevector_nonconstant_argument)
5594                        << TheCall->getArg(i)->getSourceRange());
5595 
5596     // Allow -1 which will be translated to undef in the IR.
5597     if (Result.isSigned() && Result.isAllOnesValue())
5598       continue;
5599 
5600     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5601       return ExprError(Diag(TheCall->getBeginLoc(),
5602                             diag::err_shufflevector_argument_too_large)
5603                        << TheCall->getArg(i)->getSourceRange());
5604   }
5605 
5606   SmallVector<Expr*, 32> exprs;
5607 
5608   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5609     exprs.push_back(TheCall->getArg(i));
5610     TheCall->setArg(i, nullptr);
5611   }
5612 
5613   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5614                                          TheCall->getCallee()->getBeginLoc(),
5615                                          TheCall->getRParenLoc());
5616 }
5617 
5618 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5619 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5620                                        SourceLocation BuiltinLoc,
5621                                        SourceLocation RParenLoc) {
5622   ExprValueKind VK = VK_RValue;
5623   ExprObjectKind OK = OK_Ordinary;
5624   QualType DstTy = TInfo->getType();
5625   QualType SrcTy = E->getType();
5626 
5627   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5628     return ExprError(Diag(BuiltinLoc,
5629                           diag::err_convertvector_non_vector)
5630                      << E->getSourceRange());
5631   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5632     return ExprError(Diag(BuiltinLoc,
5633                           diag::err_convertvector_non_vector_type));
5634 
5635   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5636     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5637     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5638     if (SrcElts != DstElts)
5639       return ExprError(Diag(BuiltinLoc,
5640                             diag::err_convertvector_incompatible_vector)
5641                        << E->getSourceRange());
5642   }
5643 
5644   return new (Context)
5645       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5646 }
5647 
5648 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5649 // This is declared to take (const void*, ...) and can take two
5650 // optional constant int args.
5651 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5652   unsigned NumArgs = TheCall->getNumArgs();
5653 
5654   if (NumArgs > 3)
5655     return Diag(TheCall->getEndLoc(),
5656                 diag::err_typecheck_call_too_many_args_at_most)
5657            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5658 
5659   // Argument 0 is checked for us and the remaining arguments must be
5660   // constant integers.
5661   for (unsigned i = 1; i != NumArgs; ++i)
5662     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5663       return true;
5664 
5665   return false;
5666 }
5667 
5668 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5669 // __assume does not evaluate its arguments, and should warn if its argument
5670 // has side effects.
5671 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5672   Expr *Arg = TheCall->getArg(0);
5673   if (Arg->isInstantiationDependent()) return false;
5674 
5675   if (Arg->HasSideEffects(Context))
5676     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5677         << Arg->getSourceRange()
5678         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5679 
5680   return false;
5681 }
5682 
5683 /// Handle __builtin_alloca_with_align. This is declared
5684 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5685 /// than 8.
5686 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5687   // The alignment must be a constant integer.
5688   Expr *Arg = TheCall->getArg(1);
5689 
5690   // We can't check the value of a dependent argument.
5691   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5692     if (const auto *UE =
5693             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5694       if (UE->getKind() == UETT_AlignOf)
5695         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5696             << Arg->getSourceRange();
5697 
5698     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5699 
5700     if (!Result.isPowerOf2())
5701       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5702              << Arg->getSourceRange();
5703 
5704     if (Result < Context.getCharWidth())
5705       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5706              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5707 
5708     if (Result > std::numeric_limits<int32_t>::max())
5709       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5710              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5711   }
5712 
5713   return false;
5714 }
5715 
5716 /// Handle __builtin_assume_aligned. This is declared
5717 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5718 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5719   unsigned NumArgs = TheCall->getNumArgs();
5720 
5721   if (NumArgs > 3)
5722     return Diag(TheCall->getEndLoc(),
5723                 diag::err_typecheck_call_too_many_args_at_most)
5724            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5725 
5726   // The alignment must be a constant integer.
5727   Expr *Arg = TheCall->getArg(1);
5728 
5729   // We can't check the value of a dependent argument.
5730   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5731     llvm::APSInt Result;
5732     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5733       return true;
5734 
5735     if (!Result.isPowerOf2())
5736       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5737              << Arg->getSourceRange();
5738   }
5739 
5740   if (NumArgs > 2) {
5741     ExprResult Arg(TheCall->getArg(2));
5742     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5743       Context.getSizeType(), false);
5744     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5745     if (Arg.isInvalid()) return true;
5746     TheCall->setArg(2, Arg.get());
5747   }
5748 
5749   return false;
5750 }
5751 
5752 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5753   unsigned BuiltinID =
5754       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5755   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5756 
5757   unsigned NumArgs = TheCall->getNumArgs();
5758   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5759   if (NumArgs < NumRequiredArgs) {
5760     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5761            << 0 /* function call */ << NumRequiredArgs << NumArgs
5762            << TheCall->getSourceRange();
5763   }
5764   if (NumArgs >= NumRequiredArgs + 0x100) {
5765     return Diag(TheCall->getEndLoc(),
5766                 diag::err_typecheck_call_too_many_args_at_most)
5767            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5768            << TheCall->getSourceRange();
5769   }
5770   unsigned i = 0;
5771 
5772   // For formatting call, check buffer arg.
5773   if (!IsSizeCall) {
5774     ExprResult Arg(TheCall->getArg(i));
5775     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5776         Context, Context.VoidPtrTy, false);
5777     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5778     if (Arg.isInvalid())
5779       return true;
5780     TheCall->setArg(i, Arg.get());
5781     i++;
5782   }
5783 
5784   // Check string literal arg.
5785   unsigned FormatIdx = i;
5786   {
5787     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5788     if (Arg.isInvalid())
5789       return true;
5790     TheCall->setArg(i, Arg.get());
5791     i++;
5792   }
5793 
5794   // Make sure variadic args are scalar.
5795   unsigned FirstDataArg = i;
5796   while (i < NumArgs) {
5797     ExprResult Arg = DefaultVariadicArgumentPromotion(
5798         TheCall->getArg(i), VariadicFunction, nullptr);
5799     if (Arg.isInvalid())
5800       return true;
5801     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5802     if (ArgSize.getQuantity() >= 0x100) {
5803       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5804              << i << (int)ArgSize.getQuantity() << 0xff
5805              << TheCall->getSourceRange();
5806     }
5807     TheCall->setArg(i, Arg.get());
5808     i++;
5809   }
5810 
5811   // Check formatting specifiers. NOTE: We're only doing this for the non-size
5812   // call to avoid duplicate diagnostics.
5813   if (!IsSizeCall) {
5814     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
5815     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
5816     bool Success = CheckFormatArguments(
5817         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
5818         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
5819         CheckedVarArgs);
5820     if (!Success)
5821       return true;
5822   }
5823 
5824   if (IsSizeCall) {
5825     TheCall->setType(Context.getSizeType());
5826   } else {
5827     TheCall->setType(Context.VoidPtrTy);
5828   }
5829   return false;
5830 }
5831 
5832 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
5833 /// TheCall is a constant expression.
5834 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
5835                                   llvm::APSInt &Result) {
5836   Expr *Arg = TheCall->getArg(ArgNum);
5837   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5838   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5839 
5840   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
5841 
5842   if (!Arg->isIntegerConstantExpr(Result, Context))
5843     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
5844            << FDecl->getDeclName() << Arg->getSourceRange();
5845 
5846   return false;
5847 }
5848 
5849 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
5850 /// TheCall is a constant expression in the range [Low, High].
5851 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
5852                                        int Low, int High, bool RangeIsError) {
5853   llvm::APSInt Result;
5854 
5855   // We can't check the value of a dependent argument.
5856   Expr *Arg = TheCall->getArg(ArgNum);
5857   if (Arg->isTypeDependent() || Arg->isValueDependent())
5858     return false;
5859 
5860   // Check constant-ness first.
5861   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5862     return true;
5863 
5864   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
5865     if (RangeIsError)
5866       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
5867              << Result.toString(10) << Low << High << Arg->getSourceRange();
5868     else
5869       // Defer the warning until we know if the code will be emitted so that
5870       // dead code can ignore this.
5871       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
5872                           PDiag(diag::warn_argument_invalid_range)
5873                               << Result.toString(10) << Low << High
5874                               << Arg->getSourceRange());
5875   }
5876 
5877   return false;
5878 }
5879 
5880 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
5881 /// TheCall is a constant expression is a multiple of Num..
5882 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
5883                                           unsigned Num) {
5884   llvm::APSInt Result;
5885 
5886   // We can't check the value of a dependent argument.
5887   Expr *Arg = TheCall->getArg(ArgNum);
5888   if (Arg->isTypeDependent() || Arg->isValueDependent())
5889     return false;
5890 
5891   // Check constant-ness first.
5892   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
5893     return true;
5894 
5895   if (Result.getSExtValue() % Num != 0)
5896     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
5897            << Num << Arg->getSourceRange();
5898 
5899   return false;
5900 }
5901 
5902 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
5903 /// TheCall is an ARM/AArch64 special register string literal.
5904 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
5905                                     int ArgNum, unsigned ExpectedFieldNum,
5906                                     bool AllowName) {
5907   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
5908                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
5909                       BuiltinID == ARM::BI__builtin_arm_rsr ||
5910                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
5911                       BuiltinID == ARM::BI__builtin_arm_wsr ||
5912                       BuiltinID == ARM::BI__builtin_arm_wsrp;
5913   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
5914                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
5915                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
5916                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
5917                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
5918                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
5919   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
5920 
5921   // We can't check the value of a dependent argument.
5922   Expr *Arg = TheCall->getArg(ArgNum);
5923   if (Arg->isTypeDependent() || Arg->isValueDependent())
5924     return false;
5925 
5926   // Check if the argument is a string literal.
5927   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
5928     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
5929            << Arg->getSourceRange();
5930 
5931   // Check the type of special register given.
5932   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
5933   SmallVector<StringRef, 6> Fields;
5934   Reg.split(Fields, ":");
5935 
5936   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
5937     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
5938            << Arg->getSourceRange();
5939 
5940   // If the string is the name of a register then we cannot check that it is
5941   // valid here but if the string is of one the forms described in ACLE then we
5942   // can check that the supplied fields are integers and within the valid
5943   // ranges.
5944   if (Fields.size() > 1) {
5945     bool FiveFields = Fields.size() == 5;
5946 
5947     bool ValidString = true;
5948     if (IsARMBuiltin) {
5949       ValidString &= Fields[0].startswith_lower("cp") ||
5950                      Fields[0].startswith_lower("p");
5951       if (ValidString)
5952         Fields[0] =
5953           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
5954 
5955       ValidString &= Fields[2].startswith_lower("c");
5956       if (ValidString)
5957         Fields[2] = Fields[2].drop_front(1);
5958 
5959       if (FiveFields) {
5960         ValidString &= Fields[3].startswith_lower("c");
5961         if (ValidString)
5962           Fields[3] = Fields[3].drop_front(1);
5963       }
5964     }
5965 
5966     SmallVector<int, 5> Ranges;
5967     if (FiveFields)
5968       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
5969     else
5970       Ranges.append({15, 7, 15});
5971 
5972     for (unsigned i=0; i<Fields.size(); ++i) {
5973       int IntField;
5974       ValidString &= !Fields[i].getAsInteger(10, IntField);
5975       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
5976     }
5977 
5978     if (!ValidString)
5979       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
5980              << Arg->getSourceRange();
5981   } else if (IsAArch64Builtin && Fields.size() == 1) {
5982     // If the register name is one of those that appear in the condition below
5983     // and the special register builtin being used is one of the write builtins,
5984     // then we require that the argument provided for writing to the register
5985     // is an integer constant expression. This is because it will be lowered to
5986     // an MSR (immediate) instruction, so we need to know the immediate at
5987     // compile time.
5988     if (TheCall->getNumArgs() != 2)
5989       return false;
5990 
5991     std::string RegLower = Reg.lower();
5992     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
5993         RegLower != "pan" && RegLower != "uao")
5994       return false;
5995 
5996     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
5997   }
5998 
5999   return false;
6000 }
6001 
6002 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6003 /// This checks that the target supports __builtin_longjmp and
6004 /// that val is a constant 1.
6005 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6006   if (!Context.getTargetInfo().hasSjLjLowering())
6007     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6008            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6009 
6010   Expr *Arg = TheCall->getArg(1);
6011   llvm::APSInt Result;
6012 
6013   // TODO: This is less than ideal. Overload this to take a value.
6014   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6015     return true;
6016 
6017   if (Result != 1)
6018     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6019            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6020 
6021   return false;
6022 }
6023 
6024 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6025 /// This checks that the target supports __builtin_setjmp.
6026 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6027   if (!Context.getTargetInfo().hasSjLjLowering())
6028     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6029            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6030   return false;
6031 }
6032 
6033 namespace {
6034 
6035 class UncoveredArgHandler {
6036   enum { Unknown = -1, AllCovered = -2 };
6037 
6038   signed FirstUncoveredArg = Unknown;
6039   SmallVector<const Expr *, 4> DiagnosticExprs;
6040 
6041 public:
6042   UncoveredArgHandler() = default;
6043 
6044   bool hasUncoveredArg() const {
6045     return (FirstUncoveredArg >= 0);
6046   }
6047 
6048   unsigned getUncoveredArg() const {
6049     assert(hasUncoveredArg() && "no uncovered argument");
6050     return FirstUncoveredArg;
6051   }
6052 
6053   void setAllCovered() {
6054     // A string has been found with all arguments covered, so clear out
6055     // the diagnostics.
6056     DiagnosticExprs.clear();
6057     FirstUncoveredArg = AllCovered;
6058   }
6059 
6060   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6061     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6062 
6063     // Don't update if a previous string covers all arguments.
6064     if (FirstUncoveredArg == AllCovered)
6065       return;
6066 
6067     // UncoveredArgHandler tracks the highest uncovered argument index
6068     // and with it all the strings that match this index.
6069     if (NewFirstUncoveredArg == FirstUncoveredArg)
6070       DiagnosticExprs.push_back(StrExpr);
6071     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6072       DiagnosticExprs.clear();
6073       DiagnosticExprs.push_back(StrExpr);
6074       FirstUncoveredArg = NewFirstUncoveredArg;
6075     }
6076   }
6077 
6078   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6079 };
6080 
6081 enum StringLiteralCheckType {
6082   SLCT_NotALiteral,
6083   SLCT_UncheckedLiteral,
6084   SLCT_CheckedLiteral
6085 };
6086 
6087 } // namespace
6088 
6089 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6090                                      BinaryOperatorKind BinOpKind,
6091                                      bool AddendIsRight) {
6092   unsigned BitWidth = Offset.getBitWidth();
6093   unsigned AddendBitWidth = Addend.getBitWidth();
6094   // There might be negative interim results.
6095   if (Addend.isUnsigned()) {
6096     Addend = Addend.zext(++AddendBitWidth);
6097     Addend.setIsSigned(true);
6098   }
6099   // Adjust the bit width of the APSInts.
6100   if (AddendBitWidth > BitWidth) {
6101     Offset = Offset.sext(AddendBitWidth);
6102     BitWidth = AddendBitWidth;
6103   } else if (BitWidth > AddendBitWidth) {
6104     Addend = Addend.sext(BitWidth);
6105   }
6106 
6107   bool Ov = false;
6108   llvm::APSInt ResOffset = Offset;
6109   if (BinOpKind == BO_Add)
6110     ResOffset = Offset.sadd_ov(Addend, Ov);
6111   else {
6112     assert(AddendIsRight && BinOpKind == BO_Sub &&
6113            "operator must be add or sub with addend on the right");
6114     ResOffset = Offset.ssub_ov(Addend, Ov);
6115   }
6116 
6117   // We add an offset to a pointer here so we should support an offset as big as
6118   // possible.
6119   if (Ov) {
6120     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6121            "index (intermediate) result too big");
6122     Offset = Offset.sext(2 * BitWidth);
6123     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6124     return;
6125   }
6126 
6127   Offset = ResOffset;
6128 }
6129 
6130 namespace {
6131 
6132 // This is a wrapper class around StringLiteral to support offsetted string
6133 // literals as format strings. It takes the offset into account when returning
6134 // the string and its length or the source locations to display notes correctly.
6135 class FormatStringLiteral {
6136   const StringLiteral *FExpr;
6137   int64_t Offset;
6138 
6139  public:
6140   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6141       : FExpr(fexpr), Offset(Offset) {}
6142 
6143   StringRef getString() const {
6144     return FExpr->getString().drop_front(Offset);
6145   }
6146 
6147   unsigned getByteLength() const {
6148     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6149   }
6150 
6151   unsigned getLength() const { return FExpr->getLength() - Offset; }
6152   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6153 
6154   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6155 
6156   QualType getType() const { return FExpr->getType(); }
6157 
6158   bool isAscii() const { return FExpr->isAscii(); }
6159   bool isWide() const { return FExpr->isWide(); }
6160   bool isUTF8() const { return FExpr->isUTF8(); }
6161   bool isUTF16() const { return FExpr->isUTF16(); }
6162   bool isUTF32() const { return FExpr->isUTF32(); }
6163   bool isPascal() const { return FExpr->isPascal(); }
6164 
6165   SourceLocation getLocationOfByte(
6166       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6167       const TargetInfo &Target, unsigned *StartToken = nullptr,
6168       unsigned *StartTokenByteOffset = nullptr) const {
6169     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6170                                     StartToken, StartTokenByteOffset);
6171   }
6172 
6173   SourceLocation getBeginLoc() const LLVM_READONLY {
6174     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6175   }
6176 
6177   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6178 };
6179 
6180 }  // namespace
6181 
6182 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6183                               const Expr *OrigFormatExpr,
6184                               ArrayRef<const Expr *> Args,
6185                               bool HasVAListArg, unsigned format_idx,
6186                               unsigned firstDataArg,
6187                               Sema::FormatStringType Type,
6188                               bool inFunctionCall,
6189                               Sema::VariadicCallType CallType,
6190                               llvm::SmallBitVector &CheckedVarArgs,
6191                               UncoveredArgHandler &UncoveredArg);
6192 
6193 // Determine if an expression is a string literal or constant string.
6194 // If this function returns false on the arguments to a function expecting a
6195 // format string, we will usually need to emit a warning.
6196 // True string literals are then checked by CheckFormatString.
6197 static StringLiteralCheckType
6198 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6199                       bool HasVAListArg, unsigned format_idx,
6200                       unsigned firstDataArg, Sema::FormatStringType Type,
6201                       Sema::VariadicCallType CallType, bool InFunctionCall,
6202                       llvm::SmallBitVector &CheckedVarArgs,
6203                       UncoveredArgHandler &UncoveredArg,
6204                       llvm::APSInt Offset) {
6205  tryAgain:
6206   assert(Offset.isSigned() && "invalid offset");
6207 
6208   if (E->isTypeDependent() || E->isValueDependent())
6209     return SLCT_NotALiteral;
6210 
6211   E = E->IgnoreParenCasts();
6212 
6213   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6214     // Technically -Wformat-nonliteral does not warn about this case.
6215     // The behavior of printf and friends in this case is implementation
6216     // dependent.  Ideally if the format string cannot be null then
6217     // it should have a 'nonnull' attribute in the function prototype.
6218     return SLCT_UncheckedLiteral;
6219 
6220   switch (E->getStmtClass()) {
6221   case Stmt::BinaryConditionalOperatorClass:
6222   case Stmt::ConditionalOperatorClass: {
6223     // The expression is a literal if both sub-expressions were, and it was
6224     // completely checked only if both sub-expressions were checked.
6225     const AbstractConditionalOperator *C =
6226         cast<AbstractConditionalOperator>(E);
6227 
6228     // Determine whether it is necessary to check both sub-expressions, for
6229     // example, because the condition expression is a constant that can be
6230     // evaluated at compile time.
6231     bool CheckLeft = true, CheckRight = true;
6232 
6233     bool Cond;
6234     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6235       if (Cond)
6236         CheckRight = false;
6237       else
6238         CheckLeft = false;
6239     }
6240 
6241     // We need to maintain the offsets for the right and the left hand side
6242     // separately to check if every possible indexed expression is a valid
6243     // string literal. They might have different offsets for different string
6244     // literals in the end.
6245     StringLiteralCheckType Left;
6246     if (!CheckLeft)
6247       Left = SLCT_UncheckedLiteral;
6248     else {
6249       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6250                                    HasVAListArg, format_idx, firstDataArg,
6251                                    Type, CallType, InFunctionCall,
6252                                    CheckedVarArgs, UncoveredArg, Offset);
6253       if (Left == SLCT_NotALiteral || !CheckRight) {
6254         return Left;
6255       }
6256     }
6257 
6258     StringLiteralCheckType Right =
6259         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6260                               HasVAListArg, format_idx, firstDataArg,
6261                               Type, CallType, InFunctionCall, CheckedVarArgs,
6262                               UncoveredArg, Offset);
6263 
6264     return (CheckLeft && Left < Right) ? Left : Right;
6265   }
6266 
6267   case Stmt::ImplicitCastExprClass:
6268     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6269     goto tryAgain;
6270 
6271   case Stmt::OpaqueValueExprClass:
6272     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6273       E = src;
6274       goto tryAgain;
6275     }
6276     return SLCT_NotALiteral;
6277 
6278   case Stmt::PredefinedExprClass:
6279     // While __func__, etc., are technically not string literals, they
6280     // cannot contain format specifiers and thus are not a security
6281     // liability.
6282     return SLCT_UncheckedLiteral;
6283 
6284   case Stmt::DeclRefExprClass: {
6285     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6286 
6287     // As an exception, do not flag errors for variables binding to
6288     // const string literals.
6289     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6290       bool isConstant = false;
6291       QualType T = DR->getType();
6292 
6293       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6294         isConstant = AT->getElementType().isConstant(S.Context);
6295       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6296         isConstant = T.isConstant(S.Context) &&
6297                      PT->getPointeeType().isConstant(S.Context);
6298       } else if (T->isObjCObjectPointerType()) {
6299         // In ObjC, there is usually no "const ObjectPointer" type,
6300         // so don't check if the pointee type is constant.
6301         isConstant = T.isConstant(S.Context);
6302       }
6303 
6304       if (isConstant) {
6305         if (const Expr *Init = VD->getAnyInitializer()) {
6306           // Look through initializers like const char c[] = { "foo" }
6307           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6308             if (InitList->isStringLiteralInit())
6309               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6310           }
6311           return checkFormatStringExpr(S, Init, Args,
6312                                        HasVAListArg, format_idx,
6313                                        firstDataArg, Type, CallType,
6314                                        /*InFunctionCall*/ false, CheckedVarArgs,
6315                                        UncoveredArg, Offset);
6316         }
6317       }
6318 
6319       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6320       // special check to see if the format string is a function parameter
6321       // of the function calling the printf function.  If the function
6322       // has an attribute indicating it is a printf-like function, then we
6323       // should suppress warnings concerning non-literals being used in a call
6324       // to a vprintf function.  For example:
6325       //
6326       // void
6327       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6328       //      va_list ap;
6329       //      va_start(ap, fmt);
6330       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6331       //      ...
6332       // }
6333       if (HasVAListArg) {
6334         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6335           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6336             int PVIndex = PV->getFunctionScopeIndex() + 1;
6337             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6338               // adjust for implicit parameter
6339               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6340                 if (MD->isInstance())
6341                   ++PVIndex;
6342               // We also check if the formats are compatible.
6343               // We can't pass a 'scanf' string to a 'printf' function.
6344               if (PVIndex == PVFormat->getFormatIdx() &&
6345                   Type == S.GetFormatStringType(PVFormat))
6346                 return SLCT_UncheckedLiteral;
6347             }
6348           }
6349         }
6350       }
6351     }
6352 
6353     return SLCT_NotALiteral;
6354   }
6355 
6356   case Stmt::CallExprClass:
6357   case Stmt::CXXMemberCallExprClass: {
6358     const CallExpr *CE = cast<CallExpr>(E);
6359     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6360       bool IsFirst = true;
6361       StringLiteralCheckType CommonResult;
6362       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6363         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6364         StringLiteralCheckType Result = checkFormatStringExpr(
6365             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6366             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6367         if (IsFirst) {
6368           CommonResult = Result;
6369           IsFirst = false;
6370         }
6371       }
6372       if (!IsFirst)
6373         return CommonResult;
6374 
6375       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6376         unsigned BuiltinID = FD->getBuiltinID();
6377         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6378             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6379           const Expr *Arg = CE->getArg(0);
6380           return checkFormatStringExpr(S, Arg, Args,
6381                                        HasVAListArg, format_idx,
6382                                        firstDataArg, Type, CallType,
6383                                        InFunctionCall, CheckedVarArgs,
6384                                        UncoveredArg, Offset);
6385         }
6386       }
6387     }
6388 
6389     return SLCT_NotALiteral;
6390   }
6391   case Stmt::ObjCMessageExprClass: {
6392     const auto *ME = cast<ObjCMessageExpr>(E);
6393     if (const auto *ND = ME->getMethodDecl()) {
6394       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6395         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6396         return checkFormatStringExpr(
6397             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6398             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6399       }
6400     }
6401 
6402     return SLCT_NotALiteral;
6403   }
6404   case Stmt::ObjCStringLiteralClass:
6405   case Stmt::StringLiteralClass: {
6406     const StringLiteral *StrE = nullptr;
6407 
6408     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6409       StrE = ObjCFExpr->getString();
6410     else
6411       StrE = cast<StringLiteral>(E);
6412 
6413     if (StrE) {
6414       if (Offset.isNegative() || Offset > StrE->getLength()) {
6415         // TODO: It would be better to have an explicit warning for out of
6416         // bounds literals.
6417         return SLCT_NotALiteral;
6418       }
6419       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6420       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6421                         firstDataArg, Type, InFunctionCall, CallType,
6422                         CheckedVarArgs, UncoveredArg);
6423       return SLCT_CheckedLiteral;
6424     }
6425 
6426     return SLCT_NotALiteral;
6427   }
6428   case Stmt::BinaryOperatorClass: {
6429     llvm::APSInt LResult;
6430     llvm::APSInt RResult;
6431 
6432     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6433 
6434     // A string literal + an int offset is still a string literal.
6435     if (BinOp->isAdditiveOp()) {
6436       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6437       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6438 
6439       if (LIsInt != RIsInt) {
6440         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6441 
6442         if (LIsInt) {
6443           if (BinOpKind == BO_Add) {
6444             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
6445             E = BinOp->getRHS();
6446             goto tryAgain;
6447           }
6448         } else {
6449           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
6450           E = BinOp->getLHS();
6451           goto tryAgain;
6452         }
6453       }
6454     }
6455 
6456     return SLCT_NotALiteral;
6457   }
6458   case Stmt::UnaryOperatorClass: {
6459     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6460     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6461     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6462       llvm::APSInt IndexResult;
6463       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6464         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
6465         E = ASE->getBase();
6466         goto tryAgain;
6467       }
6468     }
6469 
6470     return SLCT_NotALiteral;
6471   }
6472 
6473   default:
6474     return SLCT_NotALiteral;
6475   }
6476 }
6477 
6478 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6479   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6480       .Case("scanf", FST_Scanf)
6481       .Cases("printf", "printf0", FST_Printf)
6482       .Cases("NSString", "CFString", FST_NSString)
6483       .Case("strftime", FST_Strftime)
6484       .Case("strfmon", FST_Strfmon)
6485       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6486       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6487       .Case("os_trace", FST_OSLog)
6488       .Case("os_log", FST_OSLog)
6489       .Default(FST_Unknown);
6490 }
6491 
6492 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6493 /// functions) for correct use of format strings.
6494 /// Returns true if a format string has been fully checked.
6495 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6496                                 ArrayRef<const Expr *> Args,
6497                                 bool IsCXXMember,
6498                                 VariadicCallType CallType,
6499                                 SourceLocation Loc, SourceRange Range,
6500                                 llvm::SmallBitVector &CheckedVarArgs) {
6501   FormatStringInfo FSI;
6502   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6503     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6504                                 FSI.FirstDataArg, GetFormatStringType(Format),
6505                                 CallType, Loc, Range, CheckedVarArgs);
6506   return false;
6507 }
6508 
6509 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6510                                 bool HasVAListArg, unsigned format_idx,
6511                                 unsigned firstDataArg, FormatStringType Type,
6512                                 VariadicCallType CallType,
6513                                 SourceLocation Loc, SourceRange Range,
6514                                 llvm::SmallBitVector &CheckedVarArgs) {
6515   // CHECK: printf/scanf-like function is called with no format string.
6516   if (format_idx >= Args.size()) {
6517     Diag(Loc, diag::warn_missing_format_string) << Range;
6518     return false;
6519   }
6520 
6521   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6522 
6523   // CHECK: format string is not a string literal.
6524   //
6525   // Dynamically generated format strings are difficult to
6526   // automatically vet at compile time.  Requiring that format strings
6527   // are string literals: (1) permits the checking of format strings by
6528   // the compiler and thereby (2) can practically remove the source of
6529   // many format string exploits.
6530 
6531   // Format string can be either ObjC string (e.g. @"%d") or
6532   // C string (e.g. "%d")
6533   // ObjC string uses the same format specifiers as C string, so we can use
6534   // the same format string checking logic for both ObjC and C strings.
6535   UncoveredArgHandler UncoveredArg;
6536   StringLiteralCheckType CT =
6537       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6538                             format_idx, firstDataArg, Type, CallType,
6539                             /*IsFunctionCall*/ true, CheckedVarArgs,
6540                             UncoveredArg,
6541                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6542 
6543   // Generate a diagnostic where an uncovered argument is detected.
6544   if (UncoveredArg.hasUncoveredArg()) {
6545     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6546     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6547     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6548   }
6549 
6550   if (CT != SLCT_NotALiteral)
6551     // Literal format string found, check done!
6552     return CT == SLCT_CheckedLiteral;
6553 
6554   // Strftime is particular as it always uses a single 'time' argument,
6555   // so it is safe to pass a non-literal string.
6556   if (Type == FST_Strftime)
6557     return false;
6558 
6559   // Do not emit diag when the string param is a macro expansion and the
6560   // format is either NSString or CFString. This is a hack to prevent
6561   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6562   // which are usually used in place of NS and CF string literals.
6563   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6564   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6565     return false;
6566 
6567   // If there are no arguments specified, warn with -Wformat-security, otherwise
6568   // warn only with -Wformat-nonliteral.
6569   if (Args.size() == firstDataArg) {
6570     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6571       << OrigFormatExpr->getSourceRange();
6572     switch (Type) {
6573     default:
6574       break;
6575     case FST_Kprintf:
6576     case FST_FreeBSDKPrintf:
6577     case FST_Printf:
6578       Diag(FormatLoc, diag::note_format_security_fixit)
6579         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6580       break;
6581     case FST_NSString:
6582       Diag(FormatLoc, diag::note_format_security_fixit)
6583         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6584       break;
6585     }
6586   } else {
6587     Diag(FormatLoc, diag::warn_format_nonliteral)
6588       << OrigFormatExpr->getSourceRange();
6589   }
6590   return false;
6591 }
6592 
6593 namespace {
6594 
6595 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6596 protected:
6597   Sema &S;
6598   const FormatStringLiteral *FExpr;
6599   const Expr *OrigFormatExpr;
6600   const Sema::FormatStringType FSType;
6601   const unsigned FirstDataArg;
6602   const unsigned NumDataArgs;
6603   const char *Beg; // Start of format string.
6604   const bool HasVAListArg;
6605   ArrayRef<const Expr *> Args;
6606   unsigned FormatIdx;
6607   llvm::SmallBitVector CoveredArgs;
6608   bool usesPositionalArgs = false;
6609   bool atFirstArg = true;
6610   bool inFunctionCall;
6611   Sema::VariadicCallType CallType;
6612   llvm::SmallBitVector &CheckedVarArgs;
6613   UncoveredArgHandler &UncoveredArg;
6614 
6615 public:
6616   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6617                      const Expr *origFormatExpr,
6618                      const Sema::FormatStringType type, unsigned firstDataArg,
6619                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6620                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6621                      bool inFunctionCall, Sema::VariadicCallType callType,
6622                      llvm::SmallBitVector &CheckedVarArgs,
6623                      UncoveredArgHandler &UncoveredArg)
6624       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6625         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6626         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6627         inFunctionCall(inFunctionCall), CallType(callType),
6628         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6629     CoveredArgs.resize(numDataArgs);
6630     CoveredArgs.reset();
6631   }
6632 
6633   void DoneProcessing();
6634 
6635   void HandleIncompleteSpecifier(const char *startSpecifier,
6636                                  unsigned specifierLen) override;
6637 
6638   void HandleInvalidLengthModifier(
6639                            const analyze_format_string::FormatSpecifier &FS,
6640                            const analyze_format_string::ConversionSpecifier &CS,
6641                            const char *startSpecifier, unsigned specifierLen,
6642                            unsigned DiagID);
6643 
6644   void HandleNonStandardLengthModifier(
6645                     const analyze_format_string::FormatSpecifier &FS,
6646                     const char *startSpecifier, unsigned specifierLen);
6647 
6648   void HandleNonStandardConversionSpecifier(
6649                     const analyze_format_string::ConversionSpecifier &CS,
6650                     const char *startSpecifier, unsigned specifierLen);
6651 
6652   void HandlePosition(const char *startPos, unsigned posLen) override;
6653 
6654   void HandleInvalidPosition(const char *startSpecifier,
6655                              unsigned specifierLen,
6656                              analyze_format_string::PositionContext p) override;
6657 
6658   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6659 
6660   void HandleNullChar(const char *nullCharacter) override;
6661 
6662   template <typename Range>
6663   static void
6664   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6665                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6666                        bool IsStringLocation, Range StringRange,
6667                        ArrayRef<FixItHint> Fixit = None);
6668 
6669 protected:
6670   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6671                                         const char *startSpec,
6672                                         unsigned specifierLen,
6673                                         const char *csStart, unsigned csLen);
6674 
6675   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6676                                          const char *startSpec,
6677                                          unsigned specifierLen);
6678 
6679   SourceRange getFormatStringRange();
6680   CharSourceRange getSpecifierRange(const char *startSpecifier,
6681                                     unsigned specifierLen);
6682   SourceLocation getLocationOfByte(const char *x);
6683 
6684   const Expr *getDataArg(unsigned i) const;
6685 
6686   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6687                     const analyze_format_string::ConversionSpecifier &CS,
6688                     const char *startSpecifier, unsigned specifierLen,
6689                     unsigned argIndex);
6690 
6691   template <typename Range>
6692   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6693                             bool IsStringLocation, Range StringRange,
6694                             ArrayRef<FixItHint> Fixit = None);
6695 };
6696 
6697 } // namespace
6698 
6699 SourceRange CheckFormatHandler::getFormatStringRange() {
6700   return OrigFormatExpr->getSourceRange();
6701 }
6702 
6703 CharSourceRange CheckFormatHandler::
6704 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6705   SourceLocation Start = getLocationOfByte(startSpecifier);
6706   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6707 
6708   // Advance the end SourceLocation by one due to half-open ranges.
6709   End = End.getLocWithOffset(1);
6710 
6711   return CharSourceRange::getCharRange(Start, End);
6712 }
6713 
6714 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6715   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6716                                   S.getLangOpts(), S.Context.getTargetInfo());
6717 }
6718 
6719 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6720                                                    unsigned specifierLen){
6721   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6722                        getLocationOfByte(startSpecifier),
6723                        /*IsStringLocation*/true,
6724                        getSpecifierRange(startSpecifier, specifierLen));
6725 }
6726 
6727 void CheckFormatHandler::HandleInvalidLengthModifier(
6728     const analyze_format_string::FormatSpecifier &FS,
6729     const analyze_format_string::ConversionSpecifier &CS,
6730     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6731   using namespace analyze_format_string;
6732 
6733   const LengthModifier &LM = FS.getLengthModifier();
6734   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6735 
6736   // See if we know how to fix this length modifier.
6737   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6738   if (FixedLM) {
6739     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6740                          getLocationOfByte(LM.getStart()),
6741                          /*IsStringLocation*/true,
6742                          getSpecifierRange(startSpecifier, specifierLen));
6743 
6744     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6745       << FixedLM->toString()
6746       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6747 
6748   } else {
6749     FixItHint Hint;
6750     if (DiagID == diag::warn_format_nonsensical_length)
6751       Hint = FixItHint::CreateRemoval(LMRange);
6752 
6753     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6754                          getLocationOfByte(LM.getStart()),
6755                          /*IsStringLocation*/true,
6756                          getSpecifierRange(startSpecifier, specifierLen),
6757                          Hint);
6758   }
6759 }
6760 
6761 void CheckFormatHandler::HandleNonStandardLengthModifier(
6762     const analyze_format_string::FormatSpecifier &FS,
6763     const char *startSpecifier, unsigned specifierLen) {
6764   using namespace analyze_format_string;
6765 
6766   const LengthModifier &LM = FS.getLengthModifier();
6767   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6768 
6769   // See if we know how to fix this length modifier.
6770   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6771   if (FixedLM) {
6772     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6773                            << LM.toString() << 0,
6774                          getLocationOfByte(LM.getStart()),
6775                          /*IsStringLocation*/true,
6776                          getSpecifierRange(startSpecifier, specifierLen));
6777 
6778     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6779       << FixedLM->toString()
6780       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6781 
6782   } else {
6783     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6784                            << LM.toString() << 0,
6785                          getLocationOfByte(LM.getStart()),
6786                          /*IsStringLocation*/true,
6787                          getSpecifierRange(startSpecifier, specifierLen));
6788   }
6789 }
6790 
6791 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6792     const analyze_format_string::ConversionSpecifier &CS,
6793     const char *startSpecifier, unsigned specifierLen) {
6794   using namespace analyze_format_string;
6795 
6796   // See if we know how to fix this conversion specifier.
6797   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6798   if (FixedCS) {
6799     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6800                           << CS.toString() << /*conversion specifier*/1,
6801                          getLocationOfByte(CS.getStart()),
6802                          /*IsStringLocation*/true,
6803                          getSpecifierRange(startSpecifier, specifierLen));
6804 
6805     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6806     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6807       << FixedCS->toString()
6808       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
6809   } else {
6810     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6811                           << CS.toString() << /*conversion specifier*/1,
6812                          getLocationOfByte(CS.getStart()),
6813                          /*IsStringLocation*/true,
6814                          getSpecifierRange(startSpecifier, specifierLen));
6815   }
6816 }
6817 
6818 void CheckFormatHandler::HandlePosition(const char *startPos,
6819                                         unsigned posLen) {
6820   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
6821                                getLocationOfByte(startPos),
6822                                /*IsStringLocation*/true,
6823                                getSpecifierRange(startPos, posLen));
6824 }
6825 
6826 void
6827 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
6828                                      analyze_format_string::PositionContext p) {
6829   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
6830                          << (unsigned) p,
6831                        getLocationOfByte(startPos), /*IsStringLocation*/true,
6832                        getSpecifierRange(startPos, posLen));
6833 }
6834 
6835 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
6836                                             unsigned posLen) {
6837   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
6838                                getLocationOfByte(startPos),
6839                                /*IsStringLocation*/true,
6840                                getSpecifierRange(startPos, posLen));
6841 }
6842 
6843 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
6844   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
6845     // The presence of a null character is likely an error.
6846     EmitFormatDiagnostic(
6847       S.PDiag(diag::warn_printf_format_string_contains_null_char),
6848       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
6849       getFormatStringRange());
6850   }
6851 }
6852 
6853 // Note that this may return NULL if there was an error parsing or building
6854 // one of the argument expressions.
6855 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
6856   return Args[FirstDataArg + i];
6857 }
6858 
6859 void CheckFormatHandler::DoneProcessing() {
6860   // Does the number of data arguments exceed the number of
6861   // format conversions in the format string?
6862   if (!HasVAListArg) {
6863       // Find any arguments that weren't covered.
6864     CoveredArgs.flip();
6865     signed notCoveredArg = CoveredArgs.find_first();
6866     if (notCoveredArg >= 0) {
6867       assert((unsigned)notCoveredArg < NumDataArgs);
6868       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
6869     } else {
6870       UncoveredArg.setAllCovered();
6871     }
6872   }
6873 }
6874 
6875 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
6876                                    const Expr *ArgExpr) {
6877   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
6878          "Invalid state");
6879 
6880   if (!ArgExpr)
6881     return;
6882 
6883   SourceLocation Loc = ArgExpr->getBeginLoc();
6884 
6885   if (S.getSourceManager().isInSystemMacro(Loc))
6886     return;
6887 
6888   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
6889   for (auto E : DiagnosticExprs)
6890     PDiag << E->getSourceRange();
6891 
6892   CheckFormatHandler::EmitFormatDiagnostic(
6893                                   S, IsFunctionCall, DiagnosticExprs[0],
6894                                   PDiag, Loc, /*IsStringLocation*/false,
6895                                   DiagnosticExprs[0]->getSourceRange());
6896 }
6897 
6898 bool
6899 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
6900                                                      SourceLocation Loc,
6901                                                      const char *startSpec,
6902                                                      unsigned specifierLen,
6903                                                      const char *csStart,
6904                                                      unsigned csLen) {
6905   bool keepGoing = true;
6906   if (argIndex < NumDataArgs) {
6907     // Consider the argument coverered, even though the specifier doesn't
6908     // make sense.
6909     CoveredArgs.set(argIndex);
6910   }
6911   else {
6912     // If argIndex exceeds the number of data arguments we
6913     // don't issue a warning because that is just a cascade of warnings (and
6914     // they may have intended '%%' anyway). We don't want to continue processing
6915     // the format string after this point, however, as we will like just get
6916     // gibberish when trying to match arguments.
6917     keepGoing = false;
6918   }
6919 
6920   StringRef Specifier(csStart, csLen);
6921 
6922   // If the specifier in non-printable, it could be the first byte of a UTF-8
6923   // sequence. In that case, print the UTF-8 code point. If not, print the byte
6924   // hex value.
6925   std::string CodePointStr;
6926   if (!llvm::sys::locale::isPrint(*csStart)) {
6927     llvm::UTF32 CodePoint;
6928     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
6929     const llvm::UTF8 *E =
6930         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
6931     llvm::ConversionResult Result =
6932         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
6933 
6934     if (Result != llvm::conversionOK) {
6935       unsigned char FirstChar = *csStart;
6936       CodePoint = (llvm::UTF32)FirstChar;
6937     }
6938 
6939     llvm::raw_string_ostream OS(CodePointStr);
6940     if (CodePoint < 256)
6941       OS << "\\x" << llvm::format("%02x", CodePoint);
6942     else if (CodePoint <= 0xFFFF)
6943       OS << "\\u" << llvm::format("%04x", CodePoint);
6944     else
6945       OS << "\\U" << llvm::format("%08x", CodePoint);
6946     OS.flush();
6947     Specifier = CodePointStr;
6948   }
6949 
6950   EmitFormatDiagnostic(
6951       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
6952       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
6953 
6954   return keepGoing;
6955 }
6956 
6957 void
6958 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
6959                                                       const char *startSpec,
6960                                                       unsigned specifierLen) {
6961   EmitFormatDiagnostic(
6962     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
6963     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
6964 }
6965 
6966 bool
6967 CheckFormatHandler::CheckNumArgs(
6968   const analyze_format_string::FormatSpecifier &FS,
6969   const analyze_format_string::ConversionSpecifier &CS,
6970   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
6971 
6972   if (argIndex >= NumDataArgs) {
6973     PartialDiagnostic PDiag = FS.usesPositionalArg()
6974       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
6975            << (argIndex+1) << NumDataArgs)
6976       : S.PDiag(diag::warn_printf_insufficient_data_args);
6977     EmitFormatDiagnostic(
6978       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
6979       getSpecifierRange(startSpecifier, specifierLen));
6980 
6981     // Since more arguments than conversion tokens are given, by extension
6982     // all arguments are covered, so mark this as so.
6983     UncoveredArg.setAllCovered();
6984     return false;
6985   }
6986   return true;
6987 }
6988 
6989 template<typename Range>
6990 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
6991                                               SourceLocation Loc,
6992                                               bool IsStringLocation,
6993                                               Range StringRange,
6994                                               ArrayRef<FixItHint> FixIt) {
6995   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
6996                        Loc, IsStringLocation, StringRange, FixIt);
6997 }
6998 
6999 /// If the format string is not within the function call, emit a note
7000 /// so that the function call and string are in diagnostic messages.
7001 ///
7002 /// \param InFunctionCall if true, the format string is within the function
7003 /// call and only one diagnostic message will be produced.  Otherwise, an
7004 /// extra note will be emitted pointing to location of the format string.
7005 ///
7006 /// \param ArgumentExpr the expression that is passed as the format string
7007 /// argument in the function call.  Used for getting locations when two
7008 /// diagnostics are emitted.
7009 ///
7010 /// \param PDiag the callee should already have provided any strings for the
7011 /// diagnostic message.  This function only adds locations and fixits
7012 /// to diagnostics.
7013 ///
7014 /// \param Loc primary location for diagnostic.  If two diagnostics are
7015 /// required, one will be at Loc and a new SourceLocation will be created for
7016 /// the other one.
7017 ///
7018 /// \param IsStringLocation if true, Loc points to the format string should be
7019 /// used for the note.  Otherwise, Loc points to the argument list and will
7020 /// be used with PDiag.
7021 ///
7022 /// \param StringRange some or all of the string to highlight.  This is
7023 /// templated so it can accept either a CharSourceRange or a SourceRange.
7024 ///
7025 /// \param FixIt optional fix it hint for the format string.
7026 template <typename Range>
7027 void CheckFormatHandler::EmitFormatDiagnostic(
7028     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7029     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7030     Range StringRange, ArrayRef<FixItHint> FixIt) {
7031   if (InFunctionCall) {
7032     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7033     D << StringRange;
7034     D << FixIt;
7035   } else {
7036     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7037       << ArgumentExpr->getSourceRange();
7038 
7039     const Sema::SemaDiagnosticBuilder &Note =
7040       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7041              diag::note_format_string_defined);
7042 
7043     Note << StringRange;
7044     Note << FixIt;
7045   }
7046 }
7047 
7048 //===--- CHECK: Printf format string checking ------------------------------===//
7049 
7050 namespace {
7051 
7052 class CheckPrintfHandler : public CheckFormatHandler {
7053 public:
7054   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7055                      const Expr *origFormatExpr,
7056                      const Sema::FormatStringType type, unsigned firstDataArg,
7057                      unsigned numDataArgs, bool isObjC, const char *beg,
7058                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7059                      unsigned formatIdx, bool inFunctionCall,
7060                      Sema::VariadicCallType CallType,
7061                      llvm::SmallBitVector &CheckedVarArgs,
7062                      UncoveredArgHandler &UncoveredArg)
7063       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7064                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7065                            inFunctionCall, CallType, CheckedVarArgs,
7066                            UncoveredArg) {}
7067 
7068   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7069 
7070   /// Returns true if '%@' specifiers are allowed in the format string.
7071   bool allowsObjCArg() const {
7072     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7073            FSType == Sema::FST_OSTrace;
7074   }
7075 
7076   bool HandleInvalidPrintfConversionSpecifier(
7077                                       const analyze_printf::PrintfSpecifier &FS,
7078                                       const char *startSpecifier,
7079                                       unsigned specifierLen) override;
7080 
7081   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7082                              const char *startSpecifier,
7083                              unsigned specifierLen) override;
7084   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7085                        const char *StartSpecifier,
7086                        unsigned SpecifierLen,
7087                        const Expr *E);
7088 
7089   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7090                     const char *startSpecifier, unsigned specifierLen);
7091   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7092                            const analyze_printf::OptionalAmount &Amt,
7093                            unsigned type,
7094                            const char *startSpecifier, unsigned specifierLen);
7095   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7096                   const analyze_printf::OptionalFlag &flag,
7097                   const char *startSpecifier, unsigned specifierLen);
7098   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7099                          const analyze_printf::OptionalFlag &ignoredFlag,
7100                          const analyze_printf::OptionalFlag &flag,
7101                          const char *startSpecifier, unsigned specifierLen);
7102   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7103                            const Expr *E);
7104 
7105   void HandleEmptyObjCModifierFlag(const char *startFlag,
7106                                    unsigned flagLen) override;
7107 
7108   void HandleInvalidObjCModifierFlag(const char *startFlag,
7109                                             unsigned flagLen) override;
7110 
7111   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7112                                            const char *flagsEnd,
7113                                            const char *conversionPosition)
7114                                              override;
7115 };
7116 
7117 } // namespace
7118 
7119 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7120                                       const analyze_printf::PrintfSpecifier &FS,
7121                                       const char *startSpecifier,
7122                                       unsigned specifierLen) {
7123   const analyze_printf::PrintfConversionSpecifier &CS =
7124     FS.getConversionSpecifier();
7125 
7126   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7127                                           getLocationOfByte(CS.getStart()),
7128                                           startSpecifier, specifierLen,
7129                                           CS.getStart(), CS.getLength());
7130 }
7131 
7132 bool CheckPrintfHandler::HandleAmount(
7133                                const analyze_format_string::OptionalAmount &Amt,
7134                                unsigned k, const char *startSpecifier,
7135                                unsigned specifierLen) {
7136   if (Amt.hasDataArgument()) {
7137     if (!HasVAListArg) {
7138       unsigned argIndex = Amt.getArgIndex();
7139       if (argIndex >= NumDataArgs) {
7140         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7141                                << k,
7142                              getLocationOfByte(Amt.getStart()),
7143                              /*IsStringLocation*/true,
7144                              getSpecifierRange(startSpecifier, specifierLen));
7145         // Don't do any more checking.  We will just emit
7146         // spurious errors.
7147         return false;
7148       }
7149 
7150       // Type check the data argument.  It should be an 'int'.
7151       // Although not in conformance with C99, we also allow the argument to be
7152       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7153       // doesn't emit a warning for that case.
7154       CoveredArgs.set(argIndex);
7155       const Expr *Arg = getDataArg(argIndex);
7156       if (!Arg)
7157         return false;
7158 
7159       QualType T = Arg->getType();
7160 
7161       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7162       assert(AT.isValid());
7163 
7164       if (!AT.matchesType(S.Context, T)) {
7165         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7166                                << k << AT.getRepresentativeTypeName(S.Context)
7167                                << T << Arg->getSourceRange(),
7168                              getLocationOfByte(Amt.getStart()),
7169                              /*IsStringLocation*/true,
7170                              getSpecifierRange(startSpecifier, specifierLen));
7171         // Don't do any more checking.  We will just emit
7172         // spurious errors.
7173         return false;
7174       }
7175     }
7176   }
7177   return true;
7178 }
7179 
7180 void CheckPrintfHandler::HandleInvalidAmount(
7181                                       const analyze_printf::PrintfSpecifier &FS,
7182                                       const analyze_printf::OptionalAmount &Amt,
7183                                       unsigned type,
7184                                       const char *startSpecifier,
7185                                       unsigned specifierLen) {
7186   const analyze_printf::PrintfConversionSpecifier &CS =
7187     FS.getConversionSpecifier();
7188 
7189   FixItHint fixit =
7190     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7191       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7192                                  Amt.getConstantLength()))
7193       : FixItHint();
7194 
7195   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7196                          << type << CS.toString(),
7197                        getLocationOfByte(Amt.getStart()),
7198                        /*IsStringLocation*/true,
7199                        getSpecifierRange(startSpecifier, specifierLen),
7200                        fixit);
7201 }
7202 
7203 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7204                                     const analyze_printf::OptionalFlag &flag,
7205                                     const char *startSpecifier,
7206                                     unsigned specifierLen) {
7207   // Warn about pointless flag with a fixit removal.
7208   const analyze_printf::PrintfConversionSpecifier &CS =
7209     FS.getConversionSpecifier();
7210   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7211                          << flag.toString() << CS.toString(),
7212                        getLocationOfByte(flag.getPosition()),
7213                        /*IsStringLocation*/true,
7214                        getSpecifierRange(startSpecifier, specifierLen),
7215                        FixItHint::CreateRemoval(
7216                          getSpecifierRange(flag.getPosition(), 1)));
7217 }
7218 
7219 void CheckPrintfHandler::HandleIgnoredFlag(
7220                                 const analyze_printf::PrintfSpecifier &FS,
7221                                 const analyze_printf::OptionalFlag &ignoredFlag,
7222                                 const analyze_printf::OptionalFlag &flag,
7223                                 const char *startSpecifier,
7224                                 unsigned specifierLen) {
7225   // Warn about ignored flag with a fixit removal.
7226   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7227                          << ignoredFlag.toString() << flag.toString(),
7228                        getLocationOfByte(ignoredFlag.getPosition()),
7229                        /*IsStringLocation*/true,
7230                        getSpecifierRange(startSpecifier, specifierLen),
7231                        FixItHint::CreateRemoval(
7232                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7233 }
7234 
7235 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7236                                                      unsigned flagLen) {
7237   // Warn about an empty flag.
7238   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7239                        getLocationOfByte(startFlag),
7240                        /*IsStringLocation*/true,
7241                        getSpecifierRange(startFlag, flagLen));
7242 }
7243 
7244 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7245                                                        unsigned flagLen) {
7246   // Warn about an invalid flag.
7247   auto Range = getSpecifierRange(startFlag, flagLen);
7248   StringRef flag(startFlag, flagLen);
7249   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7250                       getLocationOfByte(startFlag),
7251                       /*IsStringLocation*/true,
7252                       Range, FixItHint::CreateRemoval(Range));
7253 }
7254 
7255 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7256     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7257     // Warn about using '[...]' without a '@' conversion.
7258     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7259     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7260     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7261                          getLocationOfByte(conversionPosition),
7262                          /*IsStringLocation*/true,
7263                          Range, FixItHint::CreateRemoval(Range));
7264 }
7265 
7266 // Determines if the specified is a C++ class or struct containing
7267 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7268 // "c_str()").
7269 template<typename MemberKind>
7270 static llvm::SmallPtrSet<MemberKind*, 1>
7271 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7272   const RecordType *RT = Ty->getAs<RecordType>();
7273   llvm::SmallPtrSet<MemberKind*, 1> Results;
7274 
7275   if (!RT)
7276     return Results;
7277   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7278   if (!RD || !RD->getDefinition())
7279     return Results;
7280 
7281   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7282                  Sema::LookupMemberName);
7283   R.suppressDiagnostics();
7284 
7285   // We just need to include all members of the right kind turned up by the
7286   // filter, at this point.
7287   if (S.LookupQualifiedName(R, RT->getDecl()))
7288     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7289       NamedDecl *decl = (*I)->getUnderlyingDecl();
7290       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7291         Results.insert(FK);
7292     }
7293   return Results;
7294 }
7295 
7296 /// Check if we could call '.c_str()' on an object.
7297 ///
7298 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7299 /// allow the call, or if it would be ambiguous).
7300 bool Sema::hasCStrMethod(const Expr *E) {
7301   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7302 
7303   MethodSet Results =
7304       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7305   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7306        MI != ME; ++MI)
7307     if ((*MI)->getMinRequiredArguments() == 0)
7308       return true;
7309   return false;
7310 }
7311 
7312 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7313 // better diagnostic if so. AT is assumed to be valid.
7314 // Returns true when a c_str() conversion method is found.
7315 bool CheckPrintfHandler::checkForCStrMembers(
7316     const analyze_printf::ArgType &AT, const Expr *E) {
7317   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7318 
7319   MethodSet Results =
7320       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7321 
7322   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7323        MI != ME; ++MI) {
7324     const CXXMethodDecl *Method = *MI;
7325     if (Method->getMinRequiredArguments() == 0 &&
7326         AT.matchesType(S.Context, Method->getReturnType())) {
7327       // FIXME: Suggest parens if the expression needs them.
7328       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7329       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7330           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7331       return true;
7332     }
7333   }
7334 
7335   return false;
7336 }
7337 
7338 bool
7339 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7340                                             &FS,
7341                                           const char *startSpecifier,
7342                                           unsigned specifierLen) {
7343   using namespace analyze_format_string;
7344   using namespace analyze_printf;
7345 
7346   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7347 
7348   if (FS.consumesDataArgument()) {
7349     if (atFirstArg) {
7350         atFirstArg = false;
7351         usesPositionalArgs = FS.usesPositionalArg();
7352     }
7353     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7354       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7355                                         startSpecifier, specifierLen);
7356       return false;
7357     }
7358   }
7359 
7360   // First check if the field width, precision, and conversion specifier
7361   // have matching data arguments.
7362   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7363                     startSpecifier, specifierLen)) {
7364     return false;
7365   }
7366 
7367   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7368                     startSpecifier, specifierLen)) {
7369     return false;
7370   }
7371 
7372   if (!CS.consumesDataArgument()) {
7373     // FIXME: Technically specifying a precision or field width here
7374     // makes no sense.  Worth issuing a warning at some point.
7375     return true;
7376   }
7377 
7378   // Consume the argument.
7379   unsigned argIndex = FS.getArgIndex();
7380   if (argIndex < NumDataArgs) {
7381     // The check to see if the argIndex is valid will come later.
7382     // We set the bit here because we may exit early from this
7383     // function if we encounter some other error.
7384     CoveredArgs.set(argIndex);
7385   }
7386 
7387   // FreeBSD kernel extensions.
7388   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7389       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7390     // We need at least two arguments.
7391     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7392       return false;
7393 
7394     // Claim the second argument.
7395     CoveredArgs.set(argIndex + 1);
7396 
7397     // Type check the first argument (int for %b, pointer for %D)
7398     const Expr *Ex = getDataArg(argIndex);
7399     const analyze_printf::ArgType &AT =
7400       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7401         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7402     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7403       EmitFormatDiagnostic(
7404           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7405               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7406               << false << Ex->getSourceRange(),
7407           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7408           getSpecifierRange(startSpecifier, specifierLen));
7409 
7410     // Type check the second argument (char * for both %b and %D)
7411     Ex = getDataArg(argIndex + 1);
7412     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7413     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7414       EmitFormatDiagnostic(
7415           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7416               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7417               << false << Ex->getSourceRange(),
7418           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7419           getSpecifierRange(startSpecifier, specifierLen));
7420 
7421      return true;
7422   }
7423 
7424   // Check for using an Objective-C specific conversion specifier
7425   // in a non-ObjC literal.
7426   if (!allowsObjCArg() && CS.isObjCArg()) {
7427     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7428                                                   specifierLen);
7429   }
7430 
7431   // %P can only be used with os_log.
7432   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7433     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7434                                                   specifierLen);
7435   }
7436 
7437   // %n is not allowed with os_log.
7438   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7439     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7440                          getLocationOfByte(CS.getStart()),
7441                          /*IsStringLocation*/ false,
7442                          getSpecifierRange(startSpecifier, specifierLen));
7443 
7444     return true;
7445   }
7446 
7447   // Only scalars are allowed for os_trace.
7448   if (FSType == Sema::FST_OSTrace &&
7449       (CS.getKind() == ConversionSpecifier::PArg ||
7450        CS.getKind() == ConversionSpecifier::sArg ||
7451        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7452     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7453                                                   specifierLen);
7454   }
7455 
7456   // Check for use of public/private annotation outside of os_log().
7457   if (FSType != Sema::FST_OSLog) {
7458     if (FS.isPublic().isSet()) {
7459       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7460                                << "public",
7461                            getLocationOfByte(FS.isPublic().getPosition()),
7462                            /*IsStringLocation*/ false,
7463                            getSpecifierRange(startSpecifier, specifierLen));
7464     }
7465     if (FS.isPrivate().isSet()) {
7466       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7467                                << "private",
7468                            getLocationOfByte(FS.isPrivate().getPosition()),
7469                            /*IsStringLocation*/ false,
7470                            getSpecifierRange(startSpecifier, specifierLen));
7471     }
7472   }
7473 
7474   // Check for invalid use of field width
7475   if (!FS.hasValidFieldWidth()) {
7476     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7477         startSpecifier, specifierLen);
7478   }
7479 
7480   // Check for invalid use of precision
7481   if (!FS.hasValidPrecision()) {
7482     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7483         startSpecifier, specifierLen);
7484   }
7485 
7486   // Precision is mandatory for %P specifier.
7487   if (CS.getKind() == ConversionSpecifier::PArg &&
7488       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7489     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7490                          getLocationOfByte(startSpecifier),
7491                          /*IsStringLocation*/ false,
7492                          getSpecifierRange(startSpecifier, specifierLen));
7493   }
7494 
7495   // Check each flag does not conflict with any other component.
7496   if (!FS.hasValidThousandsGroupingPrefix())
7497     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7498   if (!FS.hasValidLeadingZeros())
7499     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7500   if (!FS.hasValidPlusPrefix())
7501     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7502   if (!FS.hasValidSpacePrefix())
7503     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7504   if (!FS.hasValidAlternativeForm())
7505     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7506   if (!FS.hasValidLeftJustified())
7507     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7508 
7509   // Check that flags are not ignored by another flag
7510   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7511     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7512         startSpecifier, specifierLen);
7513   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7514     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7515             startSpecifier, specifierLen);
7516 
7517   // Check the length modifier is valid with the given conversion specifier.
7518   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7519     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7520                                 diag::warn_format_nonsensical_length);
7521   else if (!FS.hasStandardLengthModifier())
7522     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7523   else if (!FS.hasStandardLengthConversionCombination())
7524     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7525                                 diag::warn_format_non_standard_conversion_spec);
7526 
7527   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7528     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7529 
7530   // The remaining checks depend on the data arguments.
7531   if (HasVAListArg)
7532     return true;
7533 
7534   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7535     return false;
7536 
7537   const Expr *Arg = getDataArg(argIndex);
7538   if (!Arg)
7539     return true;
7540 
7541   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7542 }
7543 
7544 static bool requiresParensToAddCast(const Expr *E) {
7545   // FIXME: We should have a general way to reason about operator
7546   // precedence and whether parens are actually needed here.
7547   // Take care of a few common cases where they aren't.
7548   const Expr *Inside = E->IgnoreImpCasts();
7549   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7550     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7551 
7552   switch (Inside->getStmtClass()) {
7553   case Stmt::ArraySubscriptExprClass:
7554   case Stmt::CallExprClass:
7555   case Stmt::CharacterLiteralClass:
7556   case Stmt::CXXBoolLiteralExprClass:
7557   case Stmt::DeclRefExprClass:
7558   case Stmt::FloatingLiteralClass:
7559   case Stmt::IntegerLiteralClass:
7560   case Stmt::MemberExprClass:
7561   case Stmt::ObjCArrayLiteralClass:
7562   case Stmt::ObjCBoolLiteralExprClass:
7563   case Stmt::ObjCBoxedExprClass:
7564   case Stmt::ObjCDictionaryLiteralClass:
7565   case Stmt::ObjCEncodeExprClass:
7566   case Stmt::ObjCIvarRefExprClass:
7567   case Stmt::ObjCMessageExprClass:
7568   case Stmt::ObjCPropertyRefExprClass:
7569   case Stmt::ObjCStringLiteralClass:
7570   case Stmt::ObjCSubscriptRefExprClass:
7571   case Stmt::ParenExprClass:
7572   case Stmt::StringLiteralClass:
7573   case Stmt::UnaryOperatorClass:
7574     return false;
7575   default:
7576     return true;
7577   }
7578 }
7579 
7580 static std::pair<QualType, StringRef>
7581 shouldNotPrintDirectly(const ASTContext &Context,
7582                        QualType IntendedTy,
7583                        const Expr *E) {
7584   // Use a 'while' to peel off layers of typedefs.
7585   QualType TyTy = IntendedTy;
7586   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7587     StringRef Name = UserTy->getDecl()->getName();
7588     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7589       .Case("CFIndex", Context.getNSIntegerType())
7590       .Case("NSInteger", Context.getNSIntegerType())
7591       .Case("NSUInteger", Context.getNSUIntegerType())
7592       .Case("SInt32", Context.IntTy)
7593       .Case("UInt32", Context.UnsignedIntTy)
7594       .Default(QualType());
7595 
7596     if (!CastTy.isNull())
7597       return std::make_pair(CastTy, Name);
7598 
7599     TyTy = UserTy->desugar();
7600   }
7601 
7602   // Strip parens if necessary.
7603   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7604     return shouldNotPrintDirectly(Context,
7605                                   PE->getSubExpr()->getType(),
7606                                   PE->getSubExpr());
7607 
7608   // If this is a conditional expression, then its result type is constructed
7609   // via usual arithmetic conversions and thus there might be no necessary
7610   // typedef sugar there.  Recurse to operands to check for NSInteger &
7611   // Co. usage condition.
7612   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7613     QualType TrueTy, FalseTy;
7614     StringRef TrueName, FalseName;
7615 
7616     std::tie(TrueTy, TrueName) =
7617       shouldNotPrintDirectly(Context,
7618                              CO->getTrueExpr()->getType(),
7619                              CO->getTrueExpr());
7620     std::tie(FalseTy, FalseName) =
7621       shouldNotPrintDirectly(Context,
7622                              CO->getFalseExpr()->getType(),
7623                              CO->getFalseExpr());
7624 
7625     if (TrueTy == FalseTy)
7626       return std::make_pair(TrueTy, TrueName);
7627     else if (TrueTy.isNull())
7628       return std::make_pair(FalseTy, FalseName);
7629     else if (FalseTy.isNull())
7630       return std::make_pair(TrueTy, TrueName);
7631   }
7632 
7633   return std::make_pair(QualType(), StringRef());
7634 }
7635 
7636 bool
7637 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7638                                     const char *StartSpecifier,
7639                                     unsigned SpecifierLen,
7640                                     const Expr *E) {
7641   using namespace analyze_format_string;
7642   using namespace analyze_printf;
7643 
7644   // Now type check the data expression that matches the
7645   // format specifier.
7646   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7647   if (!AT.isValid())
7648     return true;
7649 
7650   QualType ExprTy = E->getType();
7651   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7652     ExprTy = TET->getUnderlyingExpr()->getType();
7653   }
7654 
7655   const analyze_printf::ArgType::MatchKind Match =
7656       AT.matchesType(S.Context, ExprTy);
7657   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7658   if (Match == analyze_printf::ArgType::Match)
7659     return true;
7660 
7661   // Look through argument promotions for our error message's reported type.
7662   // This includes the integral and floating promotions, but excludes array
7663   // and function pointer decay; seeing that an argument intended to be a
7664   // string has type 'char [6]' is probably more confusing than 'char *'.
7665   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7666     if (ICE->getCastKind() == CK_IntegralCast ||
7667         ICE->getCastKind() == CK_FloatingCast) {
7668       E = ICE->getSubExpr();
7669       ExprTy = E->getType();
7670 
7671       // Check if we didn't match because of an implicit cast from a 'char'
7672       // or 'short' to an 'int'.  This is done because printf is a varargs
7673       // function.
7674       if (ICE->getType() == S.Context.IntTy ||
7675           ICE->getType() == S.Context.UnsignedIntTy) {
7676         // All further checking is done on the subexpression.
7677         if (AT.matchesType(S.Context, ExprTy))
7678           return true;
7679       }
7680     }
7681   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7682     // Special case for 'a', which has type 'int' in C.
7683     // Note, however, that we do /not/ want to treat multibyte constants like
7684     // 'MooV' as characters! This form is deprecated but still exists.
7685     if (ExprTy == S.Context.IntTy)
7686       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7687         ExprTy = S.Context.CharTy;
7688   }
7689 
7690   // Look through enums to their underlying type.
7691   bool IsEnum = false;
7692   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7693     ExprTy = EnumTy->getDecl()->getIntegerType();
7694     IsEnum = true;
7695   }
7696 
7697   // %C in an Objective-C context prints a unichar, not a wchar_t.
7698   // If the argument is an integer of some kind, believe the %C and suggest
7699   // a cast instead of changing the conversion specifier.
7700   QualType IntendedTy = ExprTy;
7701   if (isObjCContext() &&
7702       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7703     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7704         !ExprTy->isCharType()) {
7705       // 'unichar' is defined as a typedef of unsigned short, but we should
7706       // prefer using the typedef if it is visible.
7707       IntendedTy = S.Context.UnsignedShortTy;
7708 
7709       // While we are here, check if the value is an IntegerLiteral that happens
7710       // to be within the valid range.
7711       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7712         const llvm::APInt &V = IL->getValue();
7713         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7714           return true;
7715       }
7716 
7717       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7718                           Sema::LookupOrdinaryName);
7719       if (S.LookupName(Result, S.getCurScope())) {
7720         NamedDecl *ND = Result.getFoundDecl();
7721         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7722           if (TD->getUnderlyingType() == IntendedTy)
7723             IntendedTy = S.Context.getTypedefType(TD);
7724       }
7725     }
7726   }
7727 
7728   // Special-case some of Darwin's platform-independence types by suggesting
7729   // casts to primitive types that are known to be large enough.
7730   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7731   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7732     QualType CastTy;
7733     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7734     if (!CastTy.isNull()) {
7735       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7736       // (long in ASTContext). Only complain to pedants.
7737       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7738           (AT.isSizeT() || AT.isPtrdiffT()) &&
7739           AT.matchesType(S.Context, CastTy))
7740         Pedantic = true;
7741       IntendedTy = CastTy;
7742       ShouldNotPrintDirectly = true;
7743     }
7744   }
7745 
7746   // We may be able to offer a FixItHint if it is a supported type.
7747   PrintfSpecifier fixedFS = FS;
7748   bool Success =
7749       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7750 
7751   if (Success) {
7752     // Get the fix string from the fixed format specifier
7753     SmallString<16> buf;
7754     llvm::raw_svector_ostream os(buf);
7755     fixedFS.toString(os);
7756 
7757     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7758 
7759     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7760       unsigned Diag =
7761           Pedantic
7762               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7763               : diag::warn_format_conversion_argument_type_mismatch;
7764       // In this case, the specifier is wrong and should be changed to match
7765       // the argument.
7766       EmitFormatDiagnostic(S.PDiag(Diag)
7767                                << AT.getRepresentativeTypeName(S.Context)
7768                                << IntendedTy << IsEnum << E->getSourceRange(),
7769                            E->getBeginLoc(),
7770                            /*IsStringLocation*/ false, SpecRange,
7771                            FixItHint::CreateReplacement(SpecRange, os.str()));
7772     } else {
7773       // The canonical type for formatting this value is different from the
7774       // actual type of the expression. (This occurs, for example, with Darwin's
7775       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7776       // should be printed as 'long' for 64-bit compatibility.)
7777       // Rather than emitting a normal format/argument mismatch, we want to
7778       // add a cast to the recommended type (and correct the format string
7779       // if necessary).
7780       SmallString<16> CastBuf;
7781       llvm::raw_svector_ostream CastFix(CastBuf);
7782       CastFix << "(";
7783       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
7784       CastFix << ")";
7785 
7786       SmallVector<FixItHint,4> Hints;
7787       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
7788         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
7789 
7790       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
7791         // If there's already a cast present, just replace it.
7792         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
7793         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
7794 
7795       } else if (!requiresParensToAddCast(E)) {
7796         // If the expression has high enough precedence,
7797         // just write the C-style cast.
7798         Hints.push_back(
7799             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7800       } else {
7801         // Otherwise, add parens around the expression as well as the cast.
7802         CastFix << "(";
7803         Hints.push_back(
7804             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
7805 
7806         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
7807         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
7808       }
7809 
7810       if (ShouldNotPrintDirectly) {
7811         // The expression has a type that should not be printed directly.
7812         // We extract the name from the typedef because we don't want to show
7813         // the underlying type in the diagnostic.
7814         StringRef Name;
7815         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
7816           Name = TypedefTy->getDecl()->getName();
7817         else
7818           Name = CastTyName;
7819         unsigned Diag = Pedantic
7820                             ? diag::warn_format_argument_needs_cast_pedantic
7821                             : diag::warn_format_argument_needs_cast;
7822         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
7823                                            << E->getSourceRange(),
7824                              E->getBeginLoc(), /*IsStringLocation=*/false,
7825                              SpecRange, Hints);
7826       } else {
7827         // In this case, the expression could be printed using a different
7828         // specifier, but we've decided that the specifier is probably correct
7829         // and we should cast instead. Just use the normal warning message.
7830         EmitFormatDiagnostic(
7831             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7832                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
7833                 << E->getSourceRange(),
7834             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
7835       }
7836     }
7837   } else {
7838     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
7839                                                    SpecifierLen);
7840     // Since the warning for passing non-POD types to variadic functions
7841     // was deferred until now, we emit a warning for non-POD
7842     // arguments here.
7843     switch (S.isValidVarArgType(ExprTy)) {
7844     case Sema::VAK_Valid:
7845     case Sema::VAK_ValidInCXX11: {
7846       unsigned Diag =
7847           Pedantic
7848               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7849               : diag::warn_format_conversion_argument_type_mismatch;
7850 
7851       EmitFormatDiagnostic(
7852           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
7853                         << IsEnum << CSR << E->getSourceRange(),
7854           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7855       break;
7856     }
7857     case Sema::VAK_Undefined:
7858     case Sema::VAK_MSVCUndefined:
7859       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
7860                                << S.getLangOpts().CPlusPlus11 << ExprTy
7861                                << CallType
7862                                << AT.getRepresentativeTypeName(S.Context) << CSR
7863                                << E->getSourceRange(),
7864                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7865       checkForCStrMembers(AT, E);
7866       break;
7867 
7868     case Sema::VAK_Invalid:
7869       if (ExprTy->isObjCObjectType())
7870         EmitFormatDiagnostic(
7871             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
7872                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
7873                 << AT.getRepresentativeTypeName(S.Context) << CSR
7874                 << E->getSourceRange(),
7875             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
7876       else
7877         // FIXME: If this is an initializer list, suggest removing the braces
7878         // or inserting a cast to the target type.
7879         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
7880             << isa<InitListExpr>(E) << ExprTy << CallType
7881             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
7882       break;
7883     }
7884 
7885     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
7886            "format string specifier index out of range");
7887     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
7888   }
7889 
7890   return true;
7891 }
7892 
7893 //===--- CHECK: Scanf format string checking ------------------------------===//
7894 
7895 namespace {
7896 
7897 class CheckScanfHandler : public CheckFormatHandler {
7898 public:
7899   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
7900                     const Expr *origFormatExpr, Sema::FormatStringType type,
7901                     unsigned firstDataArg, unsigned numDataArgs,
7902                     const char *beg, bool hasVAListArg,
7903                     ArrayRef<const Expr *> Args, unsigned formatIdx,
7904                     bool inFunctionCall, Sema::VariadicCallType CallType,
7905                     llvm::SmallBitVector &CheckedVarArgs,
7906                     UncoveredArgHandler &UncoveredArg)
7907       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7908                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7909                            inFunctionCall, CallType, CheckedVarArgs,
7910                            UncoveredArg) {}
7911 
7912   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
7913                             const char *startSpecifier,
7914                             unsigned specifierLen) override;
7915 
7916   bool HandleInvalidScanfConversionSpecifier(
7917           const analyze_scanf::ScanfSpecifier &FS,
7918           const char *startSpecifier,
7919           unsigned specifierLen) override;
7920 
7921   void HandleIncompleteScanList(const char *start, const char *end) override;
7922 };
7923 
7924 } // namespace
7925 
7926 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
7927                                                  const char *end) {
7928   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
7929                        getLocationOfByte(end), /*IsStringLocation*/true,
7930                        getSpecifierRange(start, end - start));
7931 }
7932 
7933 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
7934                                         const analyze_scanf::ScanfSpecifier &FS,
7935                                         const char *startSpecifier,
7936                                         unsigned specifierLen) {
7937   const analyze_scanf::ScanfConversionSpecifier &CS =
7938     FS.getConversionSpecifier();
7939 
7940   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7941                                           getLocationOfByte(CS.getStart()),
7942                                           startSpecifier, specifierLen,
7943                                           CS.getStart(), CS.getLength());
7944 }
7945 
7946 bool CheckScanfHandler::HandleScanfSpecifier(
7947                                        const analyze_scanf::ScanfSpecifier &FS,
7948                                        const char *startSpecifier,
7949                                        unsigned specifierLen) {
7950   using namespace analyze_scanf;
7951   using namespace analyze_format_string;
7952 
7953   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
7954 
7955   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
7956   // be used to decide if we are using positional arguments consistently.
7957   if (FS.consumesDataArgument()) {
7958     if (atFirstArg) {
7959       atFirstArg = false;
7960       usesPositionalArgs = FS.usesPositionalArg();
7961     }
7962     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7963       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7964                                         startSpecifier, specifierLen);
7965       return false;
7966     }
7967   }
7968 
7969   // Check if the field with is non-zero.
7970   const OptionalAmount &Amt = FS.getFieldWidth();
7971   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
7972     if (Amt.getConstantAmount() == 0) {
7973       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
7974                                                    Amt.getConstantLength());
7975       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
7976                            getLocationOfByte(Amt.getStart()),
7977                            /*IsStringLocation*/true, R,
7978                            FixItHint::CreateRemoval(R));
7979     }
7980   }
7981 
7982   if (!FS.consumesDataArgument()) {
7983     // FIXME: Technically specifying a precision or field width here
7984     // makes no sense.  Worth issuing a warning at some point.
7985     return true;
7986   }
7987 
7988   // Consume the argument.
7989   unsigned argIndex = FS.getArgIndex();
7990   if (argIndex < NumDataArgs) {
7991       // The check to see if the argIndex is valid will come later.
7992       // We set the bit here because we may exit early from this
7993       // function if we encounter some other error.
7994     CoveredArgs.set(argIndex);
7995   }
7996 
7997   // Check the length modifier is valid with the given conversion specifier.
7998   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
7999     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8000                                 diag::warn_format_nonsensical_length);
8001   else if (!FS.hasStandardLengthModifier())
8002     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8003   else if (!FS.hasStandardLengthConversionCombination())
8004     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8005                                 diag::warn_format_non_standard_conversion_spec);
8006 
8007   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8008     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8009 
8010   // The remaining checks depend on the data arguments.
8011   if (HasVAListArg)
8012     return true;
8013 
8014   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8015     return false;
8016 
8017   // Check that the argument type matches the format specifier.
8018   const Expr *Ex = getDataArg(argIndex);
8019   if (!Ex)
8020     return true;
8021 
8022   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8023 
8024   if (!AT.isValid()) {
8025     return true;
8026   }
8027 
8028   analyze_format_string::ArgType::MatchKind Match =
8029       AT.matchesType(S.Context, Ex->getType());
8030   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8031   if (Match == analyze_format_string::ArgType::Match)
8032     return true;
8033 
8034   ScanfSpecifier fixedFS = FS;
8035   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8036                                  S.getLangOpts(), S.Context);
8037 
8038   unsigned Diag =
8039       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8040                : diag::warn_format_conversion_argument_type_mismatch;
8041 
8042   if (Success) {
8043     // Get the fix string from the fixed format specifier.
8044     SmallString<128> buf;
8045     llvm::raw_svector_ostream os(buf);
8046     fixedFS.toString(os);
8047 
8048     EmitFormatDiagnostic(
8049         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8050                       << Ex->getType() << false << Ex->getSourceRange(),
8051         Ex->getBeginLoc(),
8052         /*IsStringLocation*/ false,
8053         getSpecifierRange(startSpecifier, specifierLen),
8054         FixItHint::CreateReplacement(
8055             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8056   } else {
8057     EmitFormatDiagnostic(S.PDiag(Diag)
8058                              << AT.getRepresentativeTypeName(S.Context)
8059                              << Ex->getType() << false << Ex->getSourceRange(),
8060                          Ex->getBeginLoc(),
8061                          /*IsStringLocation*/ false,
8062                          getSpecifierRange(startSpecifier, specifierLen));
8063   }
8064 
8065   return true;
8066 }
8067 
8068 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8069                               const Expr *OrigFormatExpr,
8070                               ArrayRef<const Expr *> Args,
8071                               bool HasVAListArg, unsigned format_idx,
8072                               unsigned firstDataArg,
8073                               Sema::FormatStringType Type,
8074                               bool inFunctionCall,
8075                               Sema::VariadicCallType CallType,
8076                               llvm::SmallBitVector &CheckedVarArgs,
8077                               UncoveredArgHandler &UncoveredArg) {
8078   // CHECK: is the format string a wide literal?
8079   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8080     CheckFormatHandler::EmitFormatDiagnostic(
8081         S, inFunctionCall, Args[format_idx],
8082         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8083         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8084     return;
8085   }
8086 
8087   // Str - The format string.  NOTE: this is NOT null-terminated!
8088   StringRef StrRef = FExpr->getString();
8089   const char *Str = StrRef.data();
8090   // Account for cases where the string literal is truncated in a declaration.
8091   const ConstantArrayType *T =
8092     S.Context.getAsConstantArrayType(FExpr->getType());
8093   assert(T && "String literal not of constant array type!");
8094   size_t TypeSize = T->getSize().getZExtValue();
8095   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8096   const unsigned numDataArgs = Args.size() - firstDataArg;
8097 
8098   // Emit a warning if the string literal is truncated and does not contain an
8099   // embedded null character.
8100   if (TypeSize <= StrRef.size() &&
8101       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8102     CheckFormatHandler::EmitFormatDiagnostic(
8103         S, inFunctionCall, Args[format_idx],
8104         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8105         FExpr->getBeginLoc(),
8106         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8107     return;
8108   }
8109 
8110   // CHECK: empty format string?
8111   if (StrLen == 0 && numDataArgs > 0) {
8112     CheckFormatHandler::EmitFormatDiagnostic(
8113         S, inFunctionCall, Args[format_idx],
8114         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8115         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8116     return;
8117   }
8118 
8119   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8120       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8121       Type == Sema::FST_OSTrace) {
8122     CheckPrintfHandler H(
8123         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8124         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8125         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8126         CheckedVarArgs, UncoveredArg);
8127 
8128     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8129                                                   S.getLangOpts(),
8130                                                   S.Context.getTargetInfo(),
8131                                             Type == Sema::FST_FreeBSDKPrintf))
8132       H.DoneProcessing();
8133   } else if (Type == Sema::FST_Scanf) {
8134     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8135                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8136                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8137 
8138     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8139                                                  S.getLangOpts(),
8140                                                  S.Context.getTargetInfo()))
8141       H.DoneProcessing();
8142   } // TODO: handle other formats
8143 }
8144 
8145 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8146   // Str - The format string.  NOTE: this is NOT null-terminated!
8147   StringRef StrRef = FExpr->getString();
8148   const char *Str = StrRef.data();
8149   // Account for cases where the string literal is truncated in a declaration.
8150   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8151   assert(T && "String literal not of constant array type!");
8152   size_t TypeSize = T->getSize().getZExtValue();
8153   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8154   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8155                                                          getLangOpts(),
8156                                                          Context.getTargetInfo());
8157 }
8158 
8159 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8160 
8161 // Returns the related absolute value function that is larger, of 0 if one
8162 // does not exist.
8163 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8164   switch (AbsFunction) {
8165   default:
8166     return 0;
8167 
8168   case Builtin::BI__builtin_abs:
8169     return Builtin::BI__builtin_labs;
8170   case Builtin::BI__builtin_labs:
8171     return Builtin::BI__builtin_llabs;
8172   case Builtin::BI__builtin_llabs:
8173     return 0;
8174 
8175   case Builtin::BI__builtin_fabsf:
8176     return Builtin::BI__builtin_fabs;
8177   case Builtin::BI__builtin_fabs:
8178     return Builtin::BI__builtin_fabsl;
8179   case Builtin::BI__builtin_fabsl:
8180     return 0;
8181 
8182   case Builtin::BI__builtin_cabsf:
8183     return Builtin::BI__builtin_cabs;
8184   case Builtin::BI__builtin_cabs:
8185     return Builtin::BI__builtin_cabsl;
8186   case Builtin::BI__builtin_cabsl:
8187     return 0;
8188 
8189   case Builtin::BIabs:
8190     return Builtin::BIlabs;
8191   case Builtin::BIlabs:
8192     return Builtin::BIllabs;
8193   case Builtin::BIllabs:
8194     return 0;
8195 
8196   case Builtin::BIfabsf:
8197     return Builtin::BIfabs;
8198   case Builtin::BIfabs:
8199     return Builtin::BIfabsl;
8200   case Builtin::BIfabsl:
8201     return 0;
8202 
8203   case Builtin::BIcabsf:
8204    return Builtin::BIcabs;
8205   case Builtin::BIcabs:
8206     return Builtin::BIcabsl;
8207   case Builtin::BIcabsl:
8208     return 0;
8209   }
8210 }
8211 
8212 // Returns the argument type of the absolute value function.
8213 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8214                                              unsigned AbsType) {
8215   if (AbsType == 0)
8216     return QualType();
8217 
8218   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8219   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8220   if (Error != ASTContext::GE_None)
8221     return QualType();
8222 
8223   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8224   if (!FT)
8225     return QualType();
8226 
8227   if (FT->getNumParams() != 1)
8228     return QualType();
8229 
8230   return FT->getParamType(0);
8231 }
8232 
8233 // Returns the best absolute value function, or zero, based on type and
8234 // current absolute value function.
8235 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8236                                    unsigned AbsFunctionKind) {
8237   unsigned BestKind = 0;
8238   uint64_t ArgSize = Context.getTypeSize(ArgType);
8239   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8240        Kind = getLargerAbsoluteValueFunction(Kind)) {
8241     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8242     if (Context.getTypeSize(ParamType) >= ArgSize) {
8243       if (BestKind == 0)
8244         BestKind = Kind;
8245       else if (Context.hasSameType(ParamType, ArgType)) {
8246         BestKind = Kind;
8247         break;
8248       }
8249     }
8250   }
8251   return BestKind;
8252 }
8253 
8254 enum AbsoluteValueKind {
8255   AVK_Integer,
8256   AVK_Floating,
8257   AVK_Complex
8258 };
8259 
8260 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8261   if (T->isIntegralOrEnumerationType())
8262     return AVK_Integer;
8263   if (T->isRealFloatingType())
8264     return AVK_Floating;
8265   if (T->isAnyComplexType())
8266     return AVK_Complex;
8267 
8268   llvm_unreachable("Type not integer, floating, or complex");
8269 }
8270 
8271 // Changes the absolute value function to a different type.  Preserves whether
8272 // the function is a builtin.
8273 static unsigned changeAbsFunction(unsigned AbsKind,
8274                                   AbsoluteValueKind ValueKind) {
8275   switch (ValueKind) {
8276   case AVK_Integer:
8277     switch (AbsKind) {
8278     default:
8279       return 0;
8280     case Builtin::BI__builtin_fabsf:
8281     case Builtin::BI__builtin_fabs:
8282     case Builtin::BI__builtin_fabsl:
8283     case Builtin::BI__builtin_cabsf:
8284     case Builtin::BI__builtin_cabs:
8285     case Builtin::BI__builtin_cabsl:
8286       return Builtin::BI__builtin_abs;
8287     case Builtin::BIfabsf:
8288     case Builtin::BIfabs:
8289     case Builtin::BIfabsl:
8290     case Builtin::BIcabsf:
8291     case Builtin::BIcabs:
8292     case Builtin::BIcabsl:
8293       return Builtin::BIabs;
8294     }
8295   case AVK_Floating:
8296     switch (AbsKind) {
8297     default:
8298       return 0;
8299     case Builtin::BI__builtin_abs:
8300     case Builtin::BI__builtin_labs:
8301     case Builtin::BI__builtin_llabs:
8302     case Builtin::BI__builtin_cabsf:
8303     case Builtin::BI__builtin_cabs:
8304     case Builtin::BI__builtin_cabsl:
8305       return Builtin::BI__builtin_fabsf;
8306     case Builtin::BIabs:
8307     case Builtin::BIlabs:
8308     case Builtin::BIllabs:
8309     case Builtin::BIcabsf:
8310     case Builtin::BIcabs:
8311     case Builtin::BIcabsl:
8312       return Builtin::BIfabsf;
8313     }
8314   case AVK_Complex:
8315     switch (AbsKind) {
8316     default:
8317       return 0;
8318     case Builtin::BI__builtin_abs:
8319     case Builtin::BI__builtin_labs:
8320     case Builtin::BI__builtin_llabs:
8321     case Builtin::BI__builtin_fabsf:
8322     case Builtin::BI__builtin_fabs:
8323     case Builtin::BI__builtin_fabsl:
8324       return Builtin::BI__builtin_cabsf;
8325     case Builtin::BIabs:
8326     case Builtin::BIlabs:
8327     case Builtin::BIllabs:
8328     case Builtin::BIfabsf:
8329     case Builtin::BIfabs:
8330     case Builtin::BIfabsl:
8331       return Builtin::BIcabsf;
8332     }
8333   }
8334   llvm_unreachable("Unable to convert function");
8335 }
8336 
8337 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8338   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8339   if (!FnInfo)
8340     return 0;
8341 
8342   switch (FDecl->getBuiltinID()) {
8343   default:
8344     return 0;
8345   case Builtin::BI__builtin_abs:
8346   case Builtin::BI__builtin_fabs:
8347   case Builtin::BI__builtin_fabsf:
8348   case Builtin::BI__builtin_fabsl:
8349   case Builtin::BI__builtin_labs:
8350   case Builtin::BI__builtin_llabs:
8351   case Builtin::BI__builtin_cabs:
8352   case Builtin::BI__builtin_cabsf:
8353   case Builtin::BI__builtin_cabsl:
8354   case Builtin::BIabs:
8355   case Builtin::BIlabs:
8356   case Builtin::BIllabs:
8357   case Builtin::BIfabs:
8358   case Builtin::BIfabsf:
8359   case Builtin::BIfabsl:
8360   case Builtin::BIcabs:
8361   case Builtin::BIcabsf:
8362   case Builtin::BIcabsl:
8363     return FDecl->getBuiltinID();
8364   }
8365   llvm_unreachable("Unknown Builtin type");
8366 }
8367 
8368 // If the replacement is valid, emit a note with replacement function.
8369 // Additionally, suggest including the proper header if not already included.
8370 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8371                             unsigned AbsKind, QualType ArgType) {
8372   bool EmitHeaderHint = true;
8373   const char *HeaderName = nullptr;
8374   const char *FunctionName = nullptr;
8375   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8376     FunctionName = "std::abs";
8377     if (ArgType->isIntegralOrEnumerationType()) {
8378       HeaderName = "cstdlib";
8379     } else if (ArgType->isRealFloatingType()) {
8380       HeaderName = "cmath";
8381     } else {
8382       llvm_unreachable("Invalid Type");
8383     }
8384 
8385     // Lookup all std::abs
8386     if (NamespaceDecl *Std = S.getStdNamespace()) {
8387       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8388       R.suppressDiagnostics();
8389       S.LookupQualifiedName(R, Std);
8390 
8391       for (const auto *I : R) {
8392         const FunctionDecl *FDecl = nullptr;
8393         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8394           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8395         } else {
8396           FDecl = dyn_cast<FunctionDecl>(I);
8397         }
8398         if (!FDecl)
8399           continue;
8400 
8401         // Found std::abs(), check that they are the right ones.
8402         if (FDecl->getNumParams() != 1)
8403           continue;
8404 
8405         // Check that the parameter type can handle the argument.
8406         QualType ParamType = FDecl->getParamDecl(0)->getType();
8407         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8408             S.Context.getTypeSize(ArgType) <=
8409                 S.Context.getTypeSize(ParamType)) {
8410           // Found a function, don't need the header hint.
8411           EmitHeaderHint = false;
8412           break;
8413         }
8414       }
8415     }
8416   } else {
8417     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8418     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8419 
8420     if (HeaderName) {
8421       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8422       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8423       R.suppressDiagnostics();
8424       S.LookupName(R, S.getCurScope());
8425 
8426       if (R.isSingleResult()) {
8427         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8428         if (FD && FD->getBuiltinID() == AbsKind) {
8429           EmitHeaderHint = false;
8430         } else {
8431           return;
8432         }
8433       } else if (!R.empty()) {
8434         return;
8435       }
8436     }
8437   }
8438 
8439   S.Diag(Loc, diag::note_replace_abs_function)
8440       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8441 
8442   if (!HeaderName)
8443     return;
8444 
8445   if (!EmitHeaderHint)
8446     return;
8447 
8448   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8449                                                     << FunctionName;
8450 }
8451 
8452 template <std::size_t StrLen>
8453 static bool IsStdFunction(const FunctionDecl *FDecl,
8454                           const char (&Str)[StrLen]) {
8455   if (!FDecl)
8456     return false;
8457   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8458     return false;
8459   if (!FDecl->isInStdNamespace())
8460     return false;
8461 
8462   return true;
8463 }
8464 
8465 // Warn when using the wrong abs() function.
8466 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8467                                       const FunctionDecl *FDecl) {
8468   if (Call->getNumArgs() != 1)
8469     return;
8470 
8471   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8472   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8473   if (AbsKind == 0 && !IsStdAbs)
8474     return;
8475 
8476   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8477   QualType ParamType = Call->getArg(0)->getType();
8478 
8479   // Unsigned types cannot be negative.  Suggest removing the absolute value
8480   // function call.
8481   if (ArgType->isUnsignedIntegerType()) {
8482     const char *FunctionName =
8483         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8484     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8485     Diag(Call->getExprLoc(), diag::note_remove_abs)
8486         << FunctionName
8487         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8488     return;
8489   }
8490 
8491   // Taking the absolute value of a pointer is very suspicious, they probably
8492   // wanted to index into an array, dereference a pointer, call a function, etc.
8493   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8494     unsigned DiagType = 0;
8495     if (ArgType->isFunctionType())
8496       DiagType = 1;
8497     else if (ArgType->isArrayType())
8498       DiagType = 2;
8499 
8500     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8501     return;
8502   }
8503 
8504   // std::abs has overloads which prevent most of the absolute value problems
8505   // from occurring.
8506   if (IsStdAbs)
8507     return;
8508 
8509   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8510   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8511 
8512   // The argument and parameter are the same kind.  Check if they are the right
8513   // size.
8514   if (ArgValueKind == ParamValueKind) {
8515     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8516       return;
8517 
8518     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8519     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8520         << FDecl << ArgType << ParamType;
8521 
8522     if (NewAbsKind == 0)
8523       return;
8524 
8525     emitReplacement(*this, Call->getExprLoc(),
8526                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8527     return;
8528   }
8529 
8530   // ArgValueKind != ParamValueKind
8531   // The wrong type of absolute value function was used.  Attempt to find the
8532   // proper one.
8533   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8534   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8535   if (NewAbsKind == 0)
8536     return;
8537 
8538   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8539       << FDecl << ParamValueKind << ArgValueKind;
8540 
8541   emitReplacement(*this, Call->getExprLoc(),
8542                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8543 }
8544 
8545 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8546 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8547                                 const FunctionDecl *FDecl) {
8548   if (!Call || !FDecl) return;
8549 
8550   // Ignore template specializations and macros.
8551   if (inTemplateInstantiation()) return;
8552   if (Call->getExprLoc().isMacroID()) return;
8553 
8554   // Only care about the one template argument, two function parameter std::max
8555   if (Call->getNumArgs() != 2) return;
8556   if (!IsStdFunction(FDecl, "max")) return;
8557   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8558   if (!ArgList) return;
8559   if (ArgList->size() != 1) return;
8560 
8561   // Check that template type argument is unsigned integer.
8562   const auto& TA = ArgList->get(0);
8563   if (TA.getKind() != TemplateArgument::Type) return;
8564   QualType ArgType = TA.getAsType();
8565   if (!ArgType->isUnsignedIntegerType()) return;
8566 
8567   // See if either argument is a literal zero.
8568   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8569     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8570     if (!MTE) return false;
8571     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8572     if (!Num) return false;
8573     if (Num->getValue() != 0) return false;
8574     return true;
8575   };
8576 
8577   const Expr *FirstArg = Call->getArg(0);
8578   const Expr *SecondArg = Call->getArg(1);
8579   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8580   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8581 
8582   // Only warn when exactly one argument is zero.
8583   if (IsFirstArgZero == IsSecondArgZero) return;
8584 
8585   SourceRange FirstRange = FirstArg->getSourceRange();
8586   SourceRange SecondRange = SecondArg->getSourceRange();
8587 
8588   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8589 
8590   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8591       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8592 
8593   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8594   SourceRange RemovalRange;
8595   if (IsFirstArgZero) {
8596     RemovalRange = SourceRange(FirstRange.getBegin(),
8597                                SecondRange.getBegin().getLocWithOffset(-1));
8598   } else {
8599     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8600                                SecondRange.getEnd());
8601   }
8602 
8603   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8604         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8605         << FixItHint::CreateRemoval(RemovalRange);
8606 }
8607 
8608 //===--- CHECK: Standard memory functions ---------------------------------===//
8609 
8610 /// Takes the expression passed to the size_t parameter of functions
8611 /// such as memcmp, strncat, etc and warns if it's a comparison.
8612 ///
8613 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8614 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8615                                            IdentifierInfo *FnName,
8616                                            SourceLocation FnLoc,
8617                                            SourceLocation RParenLoc) {
8618   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8619   if (!Size)
8620     return false;
8621 
8622   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8623   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8624     return false;
8625 
8626   SourceRange SizeRange = Size->getSourceRange();
8627   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8628       << SizeRange << FnName;
8629   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8630       << FnName
8631       << FixItHint::CreateInsertion(
8632              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8633       << FixItHint::CreateRemoval(RParenLoc);
8634   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8635       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8636       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8637                                     ")");
8638 
8639   return true;
8640 }
8641 
8642 /// Determine whether the given type is or contains a dynamic class type
8643 /// (e.g., whether it has a vtable).
8644 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8645                                                      bool &IsContained) {
8646   // Look through array types while ignoring qualifiers.
8647   const Type *Ty = T->getBaseElementTypeUnsafe();
8648   IsContained = false;
8649 
8650   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8651   RD = RD ? RD->getDefinition() : nullptr;
8652   if (!RD || RD->isInvalidDecl())
8653     return nullptr;
8654 
8655   if (RD->isDynamicClass())
8656     return RD;
8657 
8658   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8659   // It's impossible for a class to transitively contain itself by value, so
8660   // infinite recursion is impossible.
8661   for (auto *FD : RD->fields()) {
8662     bool SubContained;
8663     if (const CXXRecordDecl *ContainedRD =
8664             getContainedDynamicClass(FD->getType(), SubContained)) {
8665       IsContained = true;
8666       return ContainedRD;
8667     }
8668   }
8669 
8670   return nullptr;
8671 }
8672 
8673 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8674   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8675     if (Unary->getKind() == UETT_SizeOf)
8676       return Unary;
8677   return nullptr;
8678 }
8679 
8680 /// If E is a sizeof expression, returns its argument expression,
8681 /// otherwise returns NULL.
8682 static const Expr *getSizeOfExprArg(const Expr *E) {
8683   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8684     if (!SizeOf->isArgumentType())
8685       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8686   return nullptr;
8687 }
8688 
8689 /// If E is a sizeof expression, returns its argument type.
8690 static QualType getSizeOfArgType(const Expr *E) {
8691   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8692     return SizeOf->getTypeOfArgument();
8693   return QualType();
8694 }
8695 
8696 namespace {
8697 
8698 struct SearchNonTrivialToInitializeField
8699     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8700   using Super =
8701       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8702 
8703   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8704 
8705   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8706                      SourceLocation SL) {
8707     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8708       asDerived().visitArray(PDIK, AT, SL);
8709       return;
8710     }
8711 
8712     Super::visitWithKind(PDIK, FT, SL);
8713   }
8714 
8715   void visitARCStrong(QualType FT, SourceLocation SL) {
8716     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8717   }
8718   void visitARCWeak(QualType FT, SourceLocation SL) {
8719     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8720   }
8721   void visitStruct(QualType FT, SourceLocation SL) {
8722     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8723       visit(FD->getType(), FD->getLocation());
8724   }
8725   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8726                   const ArrayType *AT, SourceLocation SL) {
8727     visit(getContext().getBaseElementType(AT), SL);
8728   }
8729   void visitTrivial(QualType FT, SourceLocation SL) {}
8730 
8731   static void diag(QualType RT, const Expr *E, Sema &S) {
8732     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8733   }
8734 
8735   ASTContext &getContext() { return S.getASTContext(); }
8736 
8737   const Expr *E;
8738   Sema &S;
8739 };
8740 
8741 struct SearchNonTrivialToCopyField
8742     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8743   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8744 
8745   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8746 
8747   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8748                      SourceLocation SL) {
8749     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8750       asDerived().visitArray(PCK, AT, SL);
8751       return;
8752     }
8753 
8754     Super::visitWithKind(PCK, FT, SL);
8755   }
8756 
8757   void visitARCStrong(QualType FT, SourceLocation SL) {
8758     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8759   }
8760   void visitARCWeak(QualType FT, SourceLocation SL) {
8761     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8762   }
8763   void visitStruct(QualType FT, SourceLocation SL) {
8764     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8765       visit(FD->getType(), FD->getLocation());
8766   }
8767   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8768                   SourceLocation SL) {
8769     visit(getContext().getBaseElementType(AT), SL);
8770   }
8771   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8772                 SourceLocation SL) {}
8773   void visitTrivial(QualType FT, SourceLocation SL) {}
8774   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8775 
8776   static void diag(QualType RT, const Expr *E, Sema &S) {
8777     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
8778   }
8779 
8780   ASTContext &getContext() { return S.getASTContext(); }
8781 
8782   const Expr *E;
8783   Sema &S;
8784 };
8785 
8786 }
8787 
8788 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
8789 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
8790   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
8791 
8792   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
8793     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
8794       return false;
8795 
8796     return doesExprLikelyComputeSize(BO->getLHS()) ||
8797            doesExprLikelyComputeSize(BO->getRHS());
8798   }
8799 
8800   return getAsSizeOfExpr(SizeofExpr) != nullptr;
8801 }
8802 
8803 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
8804 ///
8805 /// \code
8806 ///   #define MACRO 0
8807 ///   foo(MACRO);
8808 ///   foo(0);
8809 /// \endcode
8810 ///
8811 /// This should return true for the first call to foo, but not for the second
8812 /// (regardless of whether foo is a macro or function).
8813 static bool isArgumentExpandedFromMacro(SourceManager &SM,
8814                                         SourceLocation CallLoc,
8815                                         SourceLocation ArgLoc) {
8816   if (!CallLoc.isMacroID())
8817     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
8818 
8819   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
8820          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
8821 }
8822 
8823 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
8824 /// last two arguments transposed.
8825 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
8826   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
8827     return;
8828 
8829   const Expr *SizeArg =
8830     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
8831 
8832   auto isLiteralZero = [](const Expr *E) {
8833     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
8834   };
8835 
8836   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
8837   SourceLocation CallLoc = Call->getRParenLoc();
8838   SourceManager &SM = S.getSourceManager();
8839   if (isLiteralZero(SizeArg) &&
8840       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
8841 
8842     SourceLocation DiagLoc = SizeArg->getExprLoc();
8843 
8844     // Some platforms #define bzero to __builtin_memset. See if this is the
8845     // case, and if so, emit a better diagnostic.
8846     if (BId == Builtin::BIbzero ||
8847         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
8848                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
8849       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
8850       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
8851     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
8852       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
8853       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
8854     }
8855     return;
8856   }
8857 
8858   // If the second argument to a memset is a sizeof expression and the third
8859   // isn't, this is also likely an error. This should catch
8860   // 'memset(buf, sizeof(buf), 0xff)'.
8861   if (BId == Builtin::BImemset &&
8862       doesExprLikelyComputeSize(Call->getArg(1)) &&
8863       !doesExprLikelyComputeSize(Call->getArg(2))) {
8864     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
8865     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
8866     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
8867     return;
8868   }
8869 }
8870 
8871 /// Check for dangerous or invalid arguments to memset().
8872 ///
8873 /// This issues warnings on known problematic, dangerous or unspecified
8874 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
8875 /// function calls.
8876 ///
8877 /// \param Call The call expression to diagnose.
8878 void Sema::CheckMemaccessArguments(const CallExpr *Call,
8879                                    unsigned BId,
8880                                    IdentifierInfo *FnName) {
8881   assert(BId != 0);
8882 
8883   // It is possible to have a non-standard definition of memset.  Validate
8884   // we have enough arguments, and if not, abort further checking.
8885   unsigned ExpectedNumArgs =
8886       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
8887   if (Call->getNumArgs() < ExpectedNumArgs)
8888     return;
8889 
8890   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
8891                       BId == Builtin::BIstrndup ? 1 : 2);
8892   unsigned LenArg =
8893       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
8894   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
8895 
8896   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
8897                                      Call->getBeginLoc(), Call->getRParenLoc()))
8898     return;
8899 
8900   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
8901   CheckMemaccessSize(*this, BId, Call);
8902 
8903   // We have special checking when the length is a sizeof expression.
8904   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
8905   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
8906   llvm::FoldingSetNodeID SizeOfArgID;
8907 
8908   // Although widely used, 'bzero' is not a standard function. Be more strict
8909   // with the argument types before allowing diagnostics and only allow the
8910   // form bzero(ptr, sizeof(...)).
8911   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8912   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
8913     return;
8914 
8915   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
8916     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
8917     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
8918 
8919     QualType DestTy = Dest->getType();
8920     QualType PointeeTy;
8921     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
8922       PointeeTy = DestPtrTy->getPointeeType();
8923 
8924       // Never warn about void type pointers. This can be used to suppress
8925       // false positives.
8926       if (PointeeTy->isVoidType())
8927         continue;
8928 
8929       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
8930       // actually comparing the expressions for equality. Because computing the
8931       // expression IDs can be expensive, we only do this if the diagnostic is
8932       // enabled.
8933       if (SizeOfArg &&
8934           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
8935                            SizeOfArg->getExprLoc())) {
8936         // We only compute IDs for expressions if the warning is enabled, and
8937         // cache the sizeof arg's ID.
8938         if (SizeOfArgID == llvm::FoldingSetNodeID())
8939           SizeOfArg->Profile(SizeOfArgID, Context, true);
8940         llvm::FoldingSetNodeID DestID;
8941         Dest->Profile(DestID, Context, true);
8942         if (DestID == SizeOfArgID) {
8943           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
8944           //       over sizeof(src) as well.
8945           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
8946           StringRef ReadableName = FnName->getName();
8947 
8948           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
8949             if (UnaryOp->getOpcode() == UO_AddrOf)
8950               ActionIdx = 1; // If its an address-of operator, just remove it.
8951           if (!PointeeTy->isIncompleteType() &&
8952               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
8953             ActionIdx = 2; // If the pointee's size is sizeof(char),
8954                            // suggest an explicit length.
8955 
8956           // If the function is defined as a builtin macro, do not show macro
8957           // expansion.
8958           SourceLocation SL = SizeOfArg->getExprLoc();
8959           SourceRange DSR = Dest->getSourceRange();
8960           SourceRange SSR = SizeOfArg->getSourceRange();
8961           SourceManager &SM = getSourceManager();
8962 
8963           if (SM.isMacroArgExpansion(SL)) {
8964             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
8965             SL = SM.getSpellingLoc(SL);
8966             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
8967                              SM.getSpellingLoc(DSR.getEnd()));
8968             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
8969                              SM.getSpellingLoc(SSR.getEnd()));
8970           }
8971 
8972           DiagRuntimeBehavior(SL, SizeOfArg,
8973                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
8974                                 << ReadableName
8975                                 << PointeeTy
8976                                 << DestTy
8977                                 << DSR
8978                                 << SSR);
8979           DiagRuntimeBehavior(SL, SizeOfArg,
8980                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
8981                                 << ActionIdx
8982                                 << SSR);
8983 
8984           break;
8985         }
8986       }
8987 
8988       // Also check for cases where the sizeof argument is the exact same
8989       // type as the memory argument, and where it points to a user-defined
8990       // record type.
8991       if (SizeOfArgTy != QualType()) {
8992         if (PointeeTy->isRecordType() &&
8993             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
8994           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
8995                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
8996                                 << FnName << SizeOfArgTy << ArgIdx
8997                                 << PointeeTy << Dest->getSourceRange()
8998                                 << LenExpr->getSourceRange());
8999           break;
9000         }
9001       }
9002     } else if (DestTy->isArrayType()) {
9003       PointeeTy = DestTy;
9004     }
9005 
9006     if (PointeeTy == QualType())
9007       continue;
9008 
9009     // Always complain about dynamic classes.
9010     bool IsContained;
9011     if (const CXXRecordDecl *ContainedRD =
9012             getContainedDynamicClass(PointeeTy, IsContained)) {
9013 
9014       unsigned OperationType = 0;
9015       // "overwritten" if we're warning about the destination for any call
9016       // but memcmp; otherwise a verb appropriate to the call.
9017       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
9018         if (BId == Builtin::BImemcpy)
9019           OperationType = 1;
9020         else if(BId == Builtin::BImemmove)
9021           OperationType = 2;
9022         else if (BId == Builtin::BImemcmp)
9023           OperationType = 3;
9024       }
9025 
9026       DiagRuntimeBehavior(
9027         Dest->getExprLoc(), Dest,
9028         PDiag(diag::warn_dyn_class_memaccess)
9029           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
9030           << FnName << IsContained << ContainedRD << OperationType
9031           << Call->getCallee()->getSourceRange());
9032     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9033              BId != Builtin::BImemset)
9034       DiagRuntimeBehavior(
9035         Dest->getExprLoc(), Dest,
9036         PDiag(diag::warn_arc_object_memaccess)
9037           << ArgIdx << FnName << PointeeTy
9038           << Call->getCallee()->getSourceRange());
9039     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9040       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9041           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9042         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9043                             PDiag(diag::warn_cstruct_memaccess)
9044                                 << ArgIdx << FnName << PointeeTy << 0);
9045         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9046       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9047                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9048         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9049                             PDiag(diag::warn_cstruct_memaccess)
9050                                 << ArgIdx << FnName << PointeeTy << 1);
9051         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9052       } else {
9053         continue;
9054       }
9055     } else
9056       continue;
9057 
9058     DiagRuntimeBehavior(
9059       Dest->getExprLoc(), Dest,
9060       PDiag(diag::note_bad_memaccess_silence)
9061         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9062     break;
9063   }
9064 }
9065 
9066 // A little helper routine: ignore addition and subtraction of integer literals.
9067 // This intentionally does not ignore all integer constant expressions because
9068 // we don't want to remove sizeof().
9069 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9070   Ex = Ex->IgnoreParenCasts();
9071 
9072   while (true) {
9073     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9074     if (!BO || !BO->isAdditiveOp())
9075       break;
9076 
9077     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9078     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9079 
9080     if (isa<IntegerLiteral>(RHS))
9081       Ex = LHS;
9082     else if (isa<IntegerLiteral>(LHS))
9083       Ex = RHS;
9084     else
9085       break;
9086   }
9087 
9088   return Ex;
9089 }
9090 
9091 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9092                                                       ASTContext &Context) {
9093   // Only handle constant-sized or VLAs, but not flexible members.
9094   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9095     // Only issue the FIXIT for arrays of size > 1.
9096     if (CAT->getSize().getSExtValue() <= 1)
9097       return false;
9098   } else if (!Ty->isVariableArrayType()) {
9099     return false;
9100   }
9101   return true;
9102 }
9103 
9104 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9105 // be the size of the source, instead of the destination.
9106 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9107                                     IdentifierInfo *FnName) {
9108 
9109   // Don't crash if the user has the wrong number of arguments
9110   unsigned NumArgs = Call->getNumArgs();
9111   if ((NumArgs != 3) && (NumArgs != 4))
9112     return;
9113 
9114   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9115   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9116   const Expr *CompareWithSrc = nullptr;
9117 
9118   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9119                                      Call->getBeginLoc(), Call->getRParenLoc()))
9120     return;
9121 
9122   // Look for 'strlcpy(dst, x, sizeof(x))'
9123   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9124     CompareWithSrc = Ex;
9125   else {
9126     // Look for 'strlcpy(dst, x, strlen(x))'
9127     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9128       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9129           SizeCall->getNumArgs() == 1)
9130         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9131     }
9132   }
9133 
9134   if (!CompareWithSrc)
9135     return;
9136 
9137   // Determine if the argument to sizeof/strlen is equal to the source
9138   // argument.  In principle there's all kinds of things you could do
9139   // here, for instance creating an == expression and evaluating it with
9140   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9141   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9142   if (!SrcArgDRE)
9143     return;
9144 
9145   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9146   if (!CompareWithSrcDRE ||
9147       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9148     return;
9149 
9150   const Expr *OriginalSizeArg = Call->getArg(2);
9151   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9152       << OriginalSizeArg->getSourceRange() << FnName;
9153 
9154   // Output a FIXIT hint if the destination is an array (rather than a
9155   // pointer to an array).  This could be enhanced to handle some
9156   // pointers if we know the actual size, like if DstArg is 'array+2'
9157   // we could say 'sizeof(array)-2'.
9158   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9159   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9160     return;
9161 
9162   SmallString<128> sizeString;
9163   llvm::raw_svector_ostream OS(sizeString);
9164   OS << "sizeof(";
9165   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9166   OS << ")";
9167 
9168   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9169       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9170                                       OS.str());
9171 }
9172 
9173 /// Check if two expressions refer to the same declaration.
9174 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9175   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9176     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9177       return D1->getDecl() == D2->getDecl();
9178   return false;
9179 }
9180 
9181 static const Expr *getStrlenExprArg(const Expr *E) {
9182   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9183     const FunctionDecl *FD = CE->getDirectCallee();
9184     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9185       return nullptr;
9186     return CE->getArg(0)->IgnoreParenCasts();
9187   }
9188   return nullptr;
9189 }
9190 
9191 // Warn on anti-patterns as the 'size' argument to strncat.
9192 // The correct size argument should look like following:
9193 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9194 void Sema::CheckStrncatArguments(const CallExpr *CE,
9195                                  IdentifierInfo *FnName) {
9196   // Don't crash if the user has the wrong number of arguments.
9197   if (CE->getNumArgs() < 3)
9198     return;
9199   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9200   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9201   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9202 
9203   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9204                                      CE->getRParenLoc()))
9205     return;
9206 
9207   // Identify common expressions, which are wrongly used as the size argument
9208   // to strncat and may lead to buffer overflows.
9209   unsigned PatternType = 0;
9210   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9211     // - sizeof(dst)
9212     if (referToTheSameDecl(SizeOfArg, DstArg))
9213       PatternType = 1;
9214     // - sizeof(src)
9215     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9216       PatternType = 2;
9217   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9218     if (BE->getOpcode() == BO_Sub) {
9219       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9220       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9221       // - sizeof(dst) - strlen(dst)
9222       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9223           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9224         PatternType = 1;
9225       // - sizeof(src) - (anything)
9226       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9227         PatternType = 2;
9228     }
9229   }
9230 
9231   if (PatternType == 0)
9232     return;
9233 
9234   // Generate the diagnostic.
9235   SourceLocation SL = LenArg->getBeginLoc();
9236   SourceRange SR = LenArg->getSourceRange();
9237   SourceManager &SM = getSourceManager();
9238 
9239   // If the function is defined as a builtin macro, do not show macro expansion.
9240   if (SM.isMacroArgExpansion(SL)) {
9241     SL = SM.getSpellingLoc(SL);
9242     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9243                      SM.getSpellingLoc(SR.getEnd()));
9244   }
9245 
9246   // Check if the destination is an array (rather than a pointer to an array).
9247   QualType DstTy = DstArg->getType();
9248   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9249                                                                     Context);
9250   if (!isKnownSizeArray) {
9251     if (PatternType == 1)
9252       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9253     else
9254       Diag(SL, diag::warn_strncat_src_size) << SR;
9255     return;
9256   }
9257 
9258   if (PatternType == 1)
9259     Diag(SL, diag::warn_strncat_large_size) << SR;
9260   else
9261     Diag(SL, diag::warn_strncat_src_size) << SR;
9262 
9263   SmallString<128> sizeString;
9264   llvm::raw_svector_ostream OS(sizeString);
9265   OS << "sizeof(";
9266   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9267   OS << ") - ";
9268   OS << "strlen(";
9269   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9270   OS << ") - 1";
9271 
9272   Diag(SL, diag::note_strncat_wrong_size)
9273     << FixItHint::CreateReplacement(SR, OS.str());
9274 }
9275 
9276 void
9277 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9278                          SourceLocation ReturnLoc,
9279                          bool isObjCMethod,
9280                          const AttrVec *Attrs,
9281                          const FunctionDecl *FD) {
9282   // Check if the return value is null but should not be.
9283   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9284        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9285       CheckNonNullExpr(*this, RetValExp))
9286     Diag(ReturnLoc, diag::warn_null_ret)
9287       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9288 
9289   // C++11 [basic.stc.dynamic.allocation]p4:
9290   //   If an allocation function declared with a non-throwing
9291   //   exception-specification fails to allocate storage, it shall return
9292   //   a null pointer. Any other allocation function that fails to allocate
9293   //   storage shall indicate failure only by throwing an exception [...]
9294   if (FD) {
9295     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9296     if (Op == OO_New || Op == OO_Array_New) {
9297       const FunctionProtoType *Proto
9298         = FD->getType()->castAs<FunctionProtoType>();
9299       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9300           CheckNonNullExpr(*this, RetValExp))
9301         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9302           << FD << getLangOpts().CPlusPlus11;
9303     }
9304   }
9305 }
9306 
9307 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9308 
9309 /// Check for comparisons of floating point operands using != and ==.
9310 /// Issue a warning if these are no self-comparisons, as they are not likely
9311 /// to do what the programmer intended.
9312 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9313   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9314   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9315 
9316   // Special case: check for x == x (which is OK).
9317   // Do not emit warnings for such cases.
9318   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9319     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9320       if (DRL->getDecl() == DRR->getDecl())
9321         return;
9322 
9323   // Special case: check for comparisons against literals that can be exactly
9324   //  represented by APFloat.  In such cases, do not emit a warning.  This
9325   //  is a heuristic: often comparison against such literals are used to
9326   //  detect if a value in a variable has not changed.  This clearly can
9327   //  lead to false negatives.
9328   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9329     if (FLL->isExact())
9330       return;
9331   } else
9332     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9333       if (FLR->isExact())
9334         return;
9335 
9336   // Check for comparisons with builtin types.
9337   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9338     if (CL->getBuiltinCallee())
9339       return;
9340 
9341   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9342     if (CR->getBuiltinCallee())
9343       return;
9344 
9345   // Emit the diagnostic.
9346   Diag(Loc, diag::warn_floatingpoint_eq)
9347     << LHS->getSourceRange() << RHS->getSourceRange();
9348 }
9349 
9350 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9351 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9352 
9353 namespace {
9354 
9355 /// Structure recording the 'active' range of an integer-valued
9356 /// expression.
9357 struct IntRange {
9358   /// The number of bits active in the int.
9359   unsigned Width;
9360 
9361   /// True if the int is known not to have negative values.
9362   bool NonNegative;
9363 
9364   IntRange(unsigned Width, bool NonNegative)
9365       : Width(Width), NonNegative(NonNegative) {}
9366 
9367   /// Returns the range of the bool type.
9368   static IntRange forBoolType() {
9369     return IntRange(1, true);
9370   }
9371 
9372   /// Returns the range of an opaque value of the given integral type.
9373   static IntRange forValueOfType(ASTContext &C, QualType T) {
9374     return forValueOfCanonicalType(C,
9375                           T->getCanonicalTypeInternal().getTypePtr());
9376   }
9377 
9378   /// Returns the range of an opaque value of a canonical integral type.
9379   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9380     assert(T->isCanonicalUnqualified());
9381 
9382     if (const VectorType *VT = dyn_cast<VectorType>(T))
9383       T = VT->getElementType().getTypePtr();
9384     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9385       T = CT->getElementType().getTypePtr();
9386     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9387       T = AT->getValueType().getTypePtr();
9388 
9389     if (!C.getLangOpts().CPlusPlus) {
9390       // For enum types in C code, use the underlying datatype.
9391       if (const EnumType *ET = dyn_cast<EnumType>(T))
9392         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9393     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9394       // For enum types in C++, use the known bit width of the enumerators.
9395       EnumDecl *Enum = ET->getDecl();
9396       // In C++11, enums can have a fixed underlying type. Use this type to
9397       // compute the range.
9398       if (Enum->isFixed()) {
9399         return IntRange(C.getIntWidth(QualType(T, 0)),
9400                         !ET->isSignedIntegerOrEnumerationType());
9401       }
9402 
9403       unsigned NumPositive = Enum->getNumPositiveBits();
9404       unsigned NumNegative = Enum->getNumNegativeBits();
9405 
9406       if (NumNegative == 0)
9407         return IntRange(NumPositive, true/*NonNegative*/);
9408       else
9409         return IntRange(std::max(NumPositive + 1, NumNegative),
9410                         false/*NonNegative*/);
9411     }
9412 
9413     const BuiltinType *BT = cast<BuiltinType>(T);
9414     assert(BT->isInteger());
9415 
9416     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9417   }
9418 
9419   /// Returns the "target" range of a canonical integral type, i.e.
9420   /// the range of values expressible in the type.
9421   ///
9422   /// This matches forValueOfCanonicalType except that enums have the
9423   /// full range of their type, not the range of their enumerators.
9424   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9425     assert(T->isCanonicalUnqualified());
9426 
9427     if (const VectorType *VT = dyn_cast<VectorType>(T))
9428       T = VT->getElementType().getTypePtr();
9429     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9430       T = CT->getElementType().getTypePtr();
9431     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9432       T = AT->getValueType().getTypePtr();
9433     if (const EnumType *ET = dyn_cast<EnumType>(T))
9434       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9435 
9436     const BuiltinType *BT = cast<BuiltinType>(T);
9437     assert(BT->isInteger());
9438 
9439     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9440   }
9441 
9442   /// Returns the supremum of two ranges: i.e. their conservative merge.
9443   static IntRange join(IntRange L, IntRange R) {
9444     return IntRange(std::max(L.Width, R.Width),
9445                     L.NonNegative && R.NonNegative);
9446   }
9447 
9448   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9449   static IntRange meet(IntRange L, IntRange R) {
9450     return IntRange(std::min(L.Width, R.Width),
9451                     L.NonNegative || R.NonNegative);
9452   }
9453 };
9454 
9455 } // namespace
9456 
9457 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9458                               unsigned MaxWidth) {
9459   if (value.isSigned() && value.isNegative())
9460     return IntRange(value.getMinSignedBits(), false);
9461 
9462   if (value.getBitWidth() > MaxWidth)
9463     value = value.trunc(MaxWidth);
9464 
9465   // isNonNegative() just checks the sign bit without considering
9466   // signedness.
9467   return IntRange(value.getActiveBits(), true);
9468 }
9469 
9470 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9471                               unsigned MaxWidth) {
9472   if (result.isInt())
9473     return GetValueRange(C, result.getInt(), MaxWidth);
9474 
9475   if (result.isVector()) {
9476     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9477     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9478       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9479       R = IntRange::join(R, El);
9480     }
9481     return R;
9482   }
9483 
9484   if (result.isComplexInt()) {
9485     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9486     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9487     return IntRange::join(R, I);
9488   }
9489 
9490   // This can happen with lossless casts to intptr_t of "based" lvalues.
9491   // Assume it might use arbitrary bits.
9492   // FIXME: The only reason we need to pass the type in here is to get
9493   // the sign right on this one case.  It would be nice if APValue
9494   // preserved this.
9495   assert(result.isLValue() || result.isAddrLabelDiff());
9496   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9497 }
9498 
9499 static QualType GetExprType(const Expr *E) {
9500   QualType Ty = E->getType();
9501   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9502     Ty = AtomicRHS->getValueType();
9503   return Ty;
9504 }
9505 
9506 /// Pseudo-evaluate the given integer expression, estimating the
9507 /// range of values it might take.
9508 ///
9509 /// \param MaxWidth - the width to which the value will be truncated
9510 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9511   E = E->IgnoreParens();
9512 
9513   // Try a full evaluation first.
9514   Expr::EvalResult result;
9515   if (E->EvaluateAsRValue(result, C))
9516     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9517 
9518   // I think we only want to look through implicit casts here; if the
9519   // user has an explicit widening cast, we should treat the value as
9520   // being of the new, wider type.
9521   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9522     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9523       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9524 
9525     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9526 
9527     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9528                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9529 
9530     // Assume that non-integer casts can span the full range of the type.
9531     if (!isIntegerCast)
9532       return OutputTypeRange;
9533 
9534     IntRange SubRange
9535       = GetExprRange(C, CE->getSubExpr(),
9536                      std::min(MaxWidth, OutputTypeRange.Width));
9537 
9538     // Bail out if the subexpr's range is as wide as the cast type.
9539     if (SubRange.Width >= OutputTypeRange.Width)
9540       return OutputTypeRange;
9541 
9542     // Otherwise, we take the smaller width, and we're non-negative if
9543     // either the output type or the subexpr is.
9544     return IntRange(SubRange.Width,
9545                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9546   }
9547 
9548   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9549     // If we can fold the condition, just take that operand.
9550     bool CondResult;
9551     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9552       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9553                                         : CO->getFalseExpr(),
9554                           MaxWidth);
9555 
9556     // Otherwise, conservatively merge.
9557     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9558     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9559     return IntRange::join(L, R);
9560   }
9561 
9562   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9563     switch (BO->getOpcode()) {
9564     case BO_Cmp:
9565       llvm_unreachable("builtin <=> should have class type");
9566 
9567     // Boolean-valued operations are single-bit and positive.
9568     case BO_LAnd:
9569     case BO_LOr:
9570     case BO_LT:
9571     case BO_GT:
9572     case BO_LE:
9573     case BO_GE:
9574     case BO_EQ:
9575     case BO_NE:
9576       return IntRange::forBoolType();
9577 
9578     // The type of the assignments is the type of the LHS, so the RHS
9579     // is not necessarily the same type.
9580     case BO_MulAssign:
9581     case BO_DivAssign:
9582     case BO_RemAssign:
9583     case BO_AddAssign:
9584     case BO_SubAssign:
9585     case BO_XorAssign:
9586     case BO_OrAssign:
9587       // TODO: bitfields?
9588       return IntRange::forValueOfType(C, GetExprType(E));
9589 
9590     // Simple assignments just pass through the RHS, which will have
9591     // been coerced to the LHS type.
9592     case BO_Assign:
9593       // TODO: bitfields?
9594       return GetExprRange(C, BO->getRHS(), MaxWidth);
9595 
9596     // Operations with opaque sources are black-listed.
9597     case BO_PtrMemD:
9598     case BO_PtrMemI:
9599       return IntRange::forValueOfType(C, GetExprType(E));
9600 
9601     // Bitwise-and uses the *infinum* of the two source ranges.
9602     case BO_And:
9603     case BO_AndAssign:
9604       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9605                             GetExprRange(C, BO->getRHS(), MaxWidth));
9606 
9607     // Left shift gets black-listed based on a judgement call.
9608     case BO_Shl:
9609       // ...except that we want to treat '1 << (blah)' as logically
9610       // positive.  It's an important idiom.
9611       if (IntegerLiteral *I
9612             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9613         if (I->getValue() == 1) {
9614           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9615           return IntRange(R.Width, /*NonNegative*/ true);
9616         }
9617       }
9618       LLVM_FALLTHROUGH;
9619 
9620     case BO_ShlAssign:
9621       return IntRange::forValueOfType(C, GetExprType(E));
9622 
9623     // Right shift by a constant can narrow its left argument.
9624     case BO_Shr:
9625     case BO_ShrAssign: {
9626       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9627 
9628       // If the shift amount is a positive constant, drop the width by
9629       // that much.
9630       llvm::APSInt shift;
9631       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9632           shift.isNonNegative()) {
9633         unsigned zext = shift.getZExtValue();
9634         if (zext >= L.Width)
9635           L.Width = (L.NonNegative ? 0 : 1);
9636         else
9637           L.Width -= zext;
9638       }
9639 
9640       return L;
9641     }
9642 
9643     // Comma acts as its right operand.
9644     case BO_Comma:
9645       return GetExprRange(C, BO->getRHS(), MaxWidth);
9646 
9647     // Black-list pointer subtractions.
9648     case BO_Sub:
9649       if (BO->getLHS()->getType()->isPointerType())
9650         return IntRange::forValueOfType(C, GetExprType(E));
9651       break;
9652 
9653     // The width of a division result is mostly determined by the size
9654     // of the LHS.
9655     case BO_Div: {
9656       // Don't 'pre-truncate' the operands.
9657       unsigned opWidth = C.getIntWidth(GetExprType(E));
9658       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9659 
9660       // If the divisor is constant, use that.
9661       llvm::APSInt divisor;
9662       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9663         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9664         if (log2 >= L.Width)
9665           L.Width = (L.NonNegative ? 0 : 1);
9666         else
9667           L.Width = std::min(L.Width - log2, MaxWidth);
9668         return L;
9669       }
9670 
9671       // Otherwise, just use the LHS's width.
9672       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9673       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9674     }
9675 
9676     // The result of a remainder can't be larger than the result of
9677     // either side.
9678     case BO_Rem: {
9679       // Don't 'pre-truncate' the operands.
9680       unsigned opWidth = C.getIntWidth(GetExprType(E));
9681       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9682       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9683 
9684       IntRange meet = IntRange::meet(L, R);
9685       meet.Width = std::min(meet.Width, MaxWidth);
9686       return meet;
9687     }
9688 
9689     // The default behavior is okay for these.
9690     case BO_Mul:
9691     case BO_Add:
9692     case BO_Xor:
9693     case BO_Or:
9694       break;
9695     }
9696 
9697     // The default case is to treat the operation as if it were closed
9698     // on the narrowest type that encompasses both operands.
9699     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9700     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9701     return IntRange::join(L, R);
9702   }
9703 
9704   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9705     switch (UO->getOpcode()) {
9706     // Boolean-valued operations are white-listed.
9707     case UO_LNot:
9708       return IntRange::forBoolType();
9709 
9710     // Operations with opaque sources are black-listed.
9711     case UO_Deref:
9712     case UO_AddrOf: // should be impossible
9713       return IntRange::forValueOfType(C, GetExprType(E));
9714 
9715     default:
9716       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9717     }
9718   }
9719 
9720   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9721     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9722 
9723   if (const auto *BitField = E->getSourceBitField())
9724     return IntRange(BitField->getBitWidthValue(C),
9725                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9726 
9727   return IntRange::forValueOfType(C, GetExprType(E));
9728 }
9729 
9730 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9731   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9732 }
9733 
9734 /// Checks whether the given value, which currently has the given
9735 /// source semantics, has the same value when coerced through the
9736 /// target semantics.
9737 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9738                                  const llvm::fltSemantics &Src,
9739                                  const llvm::fltSemantics &Tgt) {
9740   llvm::APFloat truncated = value;
9741 
9742   bool ignored;
9743   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9744   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9745 
9746   return truncated.bitwiseIsEqual(value);
9747 }
9748 
9749 /// Checks whether the given value, which currently has the given
9750 /// source semantics, has the same value when coerced through the
9751 /// target semantics.
9752 ///
9753 /// The value might be a vector of floats (or a complex number).
9754 static bool IsSameFloatAfterCast(const APValue &value,
9755                                  const llvm::fltSemantics &Src,
9756                                  const llvm::fltSemantics &Tgt) {
9757   if (value.isFloat())
9758     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9759 
9760   if (value.isVector()) {
9761     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9762       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9763         return false;
9764     return true;
9765   }
9766 
9767   assert(value.isComplexFloat());
9768   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9769           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9770 }
9771 
9772 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9773 
9774 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9775   // Suppress cases where we are comparing against an enum constant.
9776   if (const DeclRefExpr *DR =
9777       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
9778     if (isa<EnumConstantDecl>(DR->getDecl()))
9779       return true;
9780 
9781   // Suppress cases where the '0' value is expanded from a macro.
9782   if (E->getBeginLoc().isMacroID())
9783     return true;
9784 
9785   return false;
9786 }
9787 
9788 static bool isKnownToHaveUnsignedValue(Expr *E) {
9789   return E->getType()->isIntegerType() &&
9790          (!E->getType()->isSignedIntegerType() ||
9791           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
9792 }
9793 
9794 namespace {
9795 /// The promoted range of values of a type. In general this has the
9796 /// following structure:
9797 ///
9798 ///     |-----------| . . . |-----------|
9799 ///     ^           ^       ^           ^
9800 ///    Min       HoleMin  HoleMax      Max
9801 ///
9802 /// ... where there is only a hole if a signed type is promoted to unsigned
9803 /// (in which case Min and Max are the smallest and largest representable
9804 /// values).
9805 struct PromotedRange {
9806   // Min, or HoleMax if there is a hole.
9807   llvm::APSInt PromotedMin;
9808   // Max, or HoleMin if there is a hole.
9809   llvm::APSInt PromotedMax;
9810 
9811   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
9812     if (R.Width == 0)
9813       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
9814     else if (R.Width >= BitWidth && !Unsigned) {
9815       // Promotion made the type *narrower*. This happens when promoting
9816       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
9817       // Treat all values of 'signed int' as being in range for now.
9818       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
9819       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
9820     } else {
9821       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
9822                         .extOrTrunc(BitWidth);
9823       PromotedMin.setIsUnsigned(Unsigned);
9824 
9825       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
9826                         .extOrTrunc(BitWidth);
9827       PromotedMax.setIsUnsigned(Unsigned);
9828     }
9829   }
9830 
9831   // Determine whether this range is contiguous (has no hole).
9832   bool isContiguous() const { return PromotedMin <= PromotedMax; }
9833 
9834   // Where a constant value is within the range.
9835   enum ComparisonResult {
9836     LT = 0x1,
9837     LE = 0x2,
9838     GT = 0x4,
9839     GE = 0x8,
9840     EQ = 0x10,
9841     NE = 0x20,
9842     InRangeFlag = 0x40,
9843 
9844     Less = LE | LT | NE,
9845     Min = LE | InRangeFlag,
9846     InRange = InRangeFlag,
9847     Max = GE | InRangeFlag,
9848     Greater = GE | GT | NE,
9849 
9850     OnlyValue = LE | GE | EQ | InRangeFlag,
9851     InHole = NE
9852   };
9853 
9854   ComparisonResult compare(const llvm::APSInt &Value) const {
9855     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
9856            Value.isUnsigned() == PromotedMin.isUnsigned());
9857     if (!isContiguous()) {
9858       assert(Value.isUnsigned() && "discontiguous range for signed compare");
9859       if (Value.isMinValue()) return Min;
9860       if (Value.isMaxValue()) return Max;
9861       if (Value >= PromotedMin) return InRange;
9862       if (Value <= PromotedMax) return InRange;
9863       return InHole;
9864     }
9865 
9866     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
9867     case -1: return Less;
9868     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
9869     case 1:
9870       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
9871       case -1: return InRange;
9872       case 0: return Max;
9873       case 1: return Greater;
9874       }
9875     }
9876 
9877     llvm_unreachable("impossible compare result");
9878   }
9879 
9880   static llvm::Optional<StringRef>
9881   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
9882     if (Op == BO_Cmp) {
9883       ComparisonResult LTFlag = LT, GTFlag = GT;
9884       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
9885 
9886       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
9887       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
9888       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
9889       return llvm::None;
9890     }
9891 
9892     ComparisonResult TrueFlag, FalseFlag;
9893     if (Op == BO_EQ) {
9894       TrueFlag = EQ;
9895       FalseFlag = NE;
9896     } else if (Op == BO_NE) {
9897       TrueFlag = NE;
9898       FalseFlag = EQ;
9899     } else {
9900       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
9901         TrueFlag = LT;
9902         FalseFlag = GE;
9903       } else {
9904         TrueFlag = GT;
9905         FalseFlag = LE;
9906       }
9907       if (Op == BO_GE || Op == BO_LE)
9908         std::swap(TrueFlag, FalseFlag);
9909     }
9910     if (R & TrueFlag)
9911       return StringRef("true");
9912     if (R & FalseFlag)
9913       return StringRef("false");
9914     return llvm::None;
9915   }
9916 };
9917 }
9918 
9919 static bool HasEnumType(Expr *E) {
9920   // Strip off implicit integral promotions.
9921   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9922     if (ICE->getCastKind() != CK_IntegralCast &&
9923         ICE->getCastKind() != CK_NoOp)
9924       break;
9925     E = ICE->getSubExpr();
9926   }
9927 
9928   return E->getType()->isEnumeralType();
9929 }
9930 
9931 static int classifyConstantValue(Expr *Constant) {
9932   // The values of this enumeration are used in the diagnostics
9933   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
9934   enum ConstantValueKind {
9935     Miscellaneous = 0,
9936     LiteralTrue,
9937     LiteralFalse
9938   };
9939   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
9940     return BL->getValue() ? ConstantValueKind::LiteralTrue
9941                           : ConstantValueKind::LiteralFalse;
9942   return ConstantValueKind::Miscellaneous;
9943 }
9944 
9945 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
9946                                         Expr *Constant, Expr *Other,
9947                                         const llvm::APSInt &Value,
9948                                         bool RhsConstant) {
9949   if (S.inTemplateInstantiation())
9950     return false;
9951 
9952   Expr *OriginalOther = Other;
9953 
9954   Constant = Constant->IgnoreParenImpCasts();
9955   Other = Other->IgnoreParenImpCasts();
9956 
9957   // Suppress warnings on tautological comparisons between values of the same
9958   // enumeration type. There are only two ways we could warn on this:
9959   //  - If the constant is outside the range of representable values of
9960   //    the enumeration. In such a case, we should warn about the cast
9961   //    to enumeration type, not about the comparison.
9962   //  - If the constant is the maximum / minimum in-range value. For an
9963   //    enumeratin type, such comparisons can be meaningful and useful.
9964   if (Constant->getType()->isEnumeralType() &&
9965       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
9966     return false;
9967 
9968   // TODO: Investigate using GetExprRange() to get tighter bounds
9969   // on the bit ranges.
9970   QualType OtherT = Other->getType();
9971   if (const auto *AT = OtherT->getAs<AtomicType>())
9972     OtherT = AT->getValueType();
9973   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
9974 
9975   // Whether we're treating Other as being a bool because of the form of
9976   // expression despite it having another type (typically 'int' in C).
9977   bool OtherIsBooleanDespiteType =
9978       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
9979   if (OtherIsBooleanDespiteType)
9980     OtherRange = IntRange::forBoolType();
9981 
9982   // Determine the promoted range of the other type and see if a comparison of
9983   // the constant against that range is tautological.
9984   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
9985                                    Value.isUnsigned());
9986   auto Cmp = OtherPromotedRange.compare(Value);
9987   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
9988   if (!Result)
9989     return false;
9990 
9991   // Suppress the diagnostic for an in-range comparison if the constant comes
9992   // from a macro or enumerator. We don't want to diagnose
9993   //
9994   //   some_long_value <= INT_MAX
9995   //
9996   // when sizeof(int) == sizeof(long).
9997   bool InRange = Cmp & PromotedRange::InRangeFlag;
9998   if (InRange && IsEnumConstOrFromMacro(S, Constant))
9999     return false;
10000 
10001   // If this is a comparison to an enum constant, include that
10002   // constant in the diagnostic.
10003   const EnumConstantDecl *ED = nullptr;
10004   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10005     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10006 
10007   // Should be enough for uint128 (39 decimal digits)
10008   SmallString<64> PrettySourceValue;
10009   llvm::raw_svector_ostream OS(PrettySourceValue);
10010   if (ED)
10011     OS << '\'' << *ED << "' (" << Value << ")";
10012   else
10013     OS << Value;
10014 
10015   // FIXME: We use a somewhat different formatting for the in-range cases and
10016   // cases involving boolean values for historical reasons. We should pick a
10017   // consistent way of presenting these diagnostics.
10018   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10019     S.DiagRuntimeBehavior(
10020       E->getOperatorLoc(), E,
10021       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10022                        : diag::warn_tautological_bool_compare)
10023           << OS.str() << classifyConstantValue(Constant)
10024           << OtherT << OtherIsBooleanDespiteType << *Result
10025           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10026   } else {
10027     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10028                         ? (HasEnumType(OriginalOther)
10029                                ? diag::warn_unsigned_enum_always_true_comparison
10030                                : diag::warn_unsigned_always_true_comparison)
10031                         : diag::warn_tautological_constant_compare;
10032 
10033     S.Diag(E->getOperatorLoc(), Diag)
10034         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10035         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10036   }
10037 
10038   return true;
10039 }
10040 
10041 /// Analyze the operands of the given comparison.  Implements the
10042 /// fallback case from AnalyzeComparison.
10043 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10044   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10045   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10046 }
10047 
10048 /// Implements -Wsign-compare.
10049 ///
10050 /// \param E the binary operator to check for warnings
10051 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10052   // The type the comparison is being performed in.
10053   QualType T = E->getLHS()->getType();
10054 
10055   // Only analyze comparison operators where both sides have been converted to
10056   // the same type.
10057   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10058     return AnalyzeImpConvsInComparison(S, E);
10059 
10060   // Don't analyze value-dependent comparisons directly.
10061   if (E->isValueDependent())
10062     return AnalyzeImpConvsInComparison(S, E);
10063 
10064   Expr *LHS = E->getLHS();
10065   Expr *RHS = E->getRHS();
10066 
10067   if (T->isIntegralType(S.Context)) {
10068     llvm::APSInt RHSValue;
10069     llvm::APSInt LHSValue;
10070 
10071     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10072     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10073 
10074     // We don't care about expressions whose result is a constant.
10075     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10076       return AnalyzeImpConvsInComparison(S, E);
10077 
10078     // We only care about expressions where just one side is literal
10079     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10080       // Is the constant on the RHS or LHS?
10081       const bool RhsConstant = IsRHSIntegralLiteral;
10082       Expr *Const = RhsConstant ? RHS : LHS;
10083       Expr *Other = RhsConstant ? LHS : RHS;
10084       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10085 
10086       // Check whether an integer constant comparison results in a value
10087       // of 'true' or 'false'.
10088       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10089         return AnalyzeImpConvsInComparison(S, E);
10090     }
10091   }
10092 
10093   if (!T->hasUnsignedIntegerRepresentation()) {
10094     // We don't do anything special if this isn't an unsigned integral
10095     // comparison:  we're only interested in integral comparisons, and
10096     // signed comparisons only happen in cases we don't care to warn about.
10097     return AnalyzeImpConvsInComparison(S, E);
10098   }
10099 
10100   LHS = LHS->IgnoreParenImpCasts();
10101   RHS = RHS->IgnoreParenImpCasts();
10102 
10103   if (!S.getLangOpts().CPlusPlus) {
10104     // Avoid warning about comparison of integers with different signs when
10105     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10106     // the type of `E`.
10107     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10108       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10109     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10110       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10111   }
10112 
10113   // Check to see if one of the (unmodified) operands is of different
10114   // signedness.
10115   Expr *signedOperand, *unsignedOperand;
10116   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10117     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10118            "unsigned comparison between two signed integer expressions?");
10119     signedOperand = LHS;
10120     unsignedOperand = RHS;
10121   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10122     signedOperand = RHS;
10123     unsignedOperand = LHS;
10124   } else {
10125     return AnalyzeImpConvsInComparison(S, E);
10126   }
10127 
10128   // Otherwise, calculate the effective range of the signed operand.
10129   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10130 
10131   // Go ahead and analyze implicit conversions in the operands.  Note
10132   // that we skip the implicit conversions on both sides.
10133   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10134   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10135 
10136   // If the signed range is non-negative, -Wsign-compare won't fire.
10137   if (signedRange.NonNegative)
10138     return;
10139 
10140   // For (in)equality comparisons, if the unsigned operand is a
10141   // constant which cannot collide with a overflowed signed operand,
10142   // then reinterpreting the signed operand as unsigned will not
10143   // change the result of the comparison.
10144   if (E->isEqualityOp()) {
10145     unsigned comparisonWidth = S.Context.getIntWidth(T);
10146     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10147 
10148     // We should never be unable to prove that the unsigned operand is
10149     // non-negative.
10150     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10151 
10152     if (unsignedRange.Width < comparisonWidth)
10153       return;
10154   }
10155 
10156   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10157     S.PDiag(diag::warn_mixed_sign_comparison)
10158       << LHS->getType() << RHS->getType()
10159       << LHS->getSourceRange() << RHS->getSourceRange());
10160 }
10161 
10162 /// Analyzes an attempt to assign the given value to a bitfield.
10163 ///
10164 /// Returns true if there was something fishy about the attempt.
10165 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10166                                       SourceLocation InitLoc) {
10167   assert(Bitfield->isBitField());
10168   if (Bitfield->isInvalidDecl())
10169     return false;
10170 
10171   // White-list bool bitfields.
10172   QualType BitfieldType = Bitfield->getType();
10173   if (BitfieldType->isBooleanType())
10174      return false;
10175 
10176   if (BitfieldType->isEnumeralType()) {
10177     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10178     // If the underlying enum type was not explicitly specified as an unsigned
10179     // type and the enum contain only positive values, MSVC++ will cause an
10180     // inconsistency by storing this as a signed type.
10181     if (S.getLangOpts().CPlusPlus11 &&
10182         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10183         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10184         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10185       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10186         << BitfieldEnumDecl->getNameAsString();
10187     }
10188   }
10189 
10190   if (Bitfield->getType()->isBooleanType())
10191     return false;
10192 
10193   // Ignore value- or type-dependent expressions.
10194   if (Bitfield->getBitWidth()->isValueDependent() ||
10195       Bitfield->getBitWidth()->isTypeDependent() ||
10196       Init->isValueDependent() ||
10197       Init->isTypeDependent())
10198     return false;
10199 
10200   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10201   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10202 
10203   llvm::APSInt Value;
10204   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
10205                                    Expr::SE_AllowSideEffects)) {
10206     // The RHS is not constant.  If the RHS has an enum type, make sure the
10207     // bitfield is wide enough to hold all the values of the enum without
10208     // truncation.
10209     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10210       EnumDecl *ED = EnumTy->getDecl();
10211       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10212 
10213       // Enum types are implicitly signed on Windows, so check if there are any
10214       // negative enumerators to see if the enum was intended to be signed or
10215       // not.
10216       bool SignedEnum = ED->getNumNegativeBits() > 0;
10217 
10218       // Check for surprising sign changes when assigning enum values to a
10219       // bitfield of different signedness.  If the bitfield is signed and we
10220       // have exactly the right number of bits to store this unsigned enum,
10221       // suggest changing the enum to an unsigned type. This typically happens
10222       // on Windows where unfixed enums always use an underlying type of 'int'.
10223       unsigned DiagID = 0;
10224       if (SignedEnum && !SignedBitfield) {
10225         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10226       } else if (SignedBitfield && !SignedEnum &&
10227                  ED->getNumPositiveBits() == FieldWidth) {
10228         DiagID = diag::warn_signed_bitfield_enum_conversion;
10229       }
10230 
10231       if (DiagID) {
10232         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10233         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10234         SourceRange TypeRange =
10235             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10236         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10237             << SignedEnum << TypeRange;
10238       }
10239 
10240       // Compute the required bitwidth. If the enum has negative values, we need
10241       // one more bit than the normal number of positive bits to represent the
10242       // sign bit.
10243       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10244                                                   ED->getNumNegativeBits())
10245                                        : ED->getNumPositiveBits();
10246 
10247       // Check the bitwidth.
10248       if (BitsNeeded > FieldWidth) {
10249         Expr *WidthExpr = Bitfield->getBitWidth();
10250         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10251             << Bitfield << ED;
10252         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10253             << BitsNeeded << ED << WidthExpr->getSourceRange();
10254       }
10255     }
10256 
10257     return false;
10258   }
10259 
10260   unsigned OriginalWidth = Value.getBitWidth();
10261 
10262   if (!Value.isSigned() || Value.isNegative())
10263     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10264       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10265         OriginalWidth = Value.getMinSignedBits();
10266 
10267   if (OriginalWidth <= FieldWidth)
10268     return false;
10269 
10270   // Compute the value which the bitfield will contain.
10271   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10272   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10273 
10274   // Check whether the stored value is equal to the original value.
10275   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10276   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10277     return false;
10278 
10279   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10280   // therefore don't strictly fit into a signed bitfield of width 1.
10281   if (FieldWidth == 1 && Value == 1)
10282     return false;
10283 
10284   std::string PrettyValue = Value.toString(10);
10285   std::string PrettyTrunc = TruncatedValue.toString(10);
10286 
10287   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10288     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10289     << Init->getSourceRange();
10290 
10291   return true;
10292 }
10293 
10294 /// Analyze the given simple or compound assignment for warning-worthy
10295 /// operations.
10296 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10297   // Just recurse on the LHS.
10298   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10299 
10300   // We want to recurse on the RHS as normal unless we're assigning to
10301   // a bitfield.
10302   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10303     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10304                                   E->getOperatorLoc())) {
10305       // Recurse, ignoring any implicit conversions on the RHS.
10306       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10307                                         E->getOperatorLoc());
10308     }
10309   }
10310 
10311   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10312 
10313   // Diagnose implicitly sequentially-consistent atomic assignment.
10314   if (E->getLHS()->getType()->isAtomicType())
10315     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10316 }
10317 
10318 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10319 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10320                             SourceLocation CContext, unsigned diag,
10321                             bool pruneControlFlow = false) {
10322   if (pruneControlFlow) {
10323     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10324                           S.PDiag(diag)
10325                             << SourceType << T << E->getSourceRange()
10326                             << SourceRange(CContext));
10327     return;
10328   }
10329   S.Diag(E->getExprLoc(), diag)
10330     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10331 }
10332 
10333 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10334 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10335                             SourceLocation CContext,
10336                             unsigned diag, bool pruneControlFlow = false) {
10337   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10338 }
10339 
10340 /// Diagnose an implicit cast from a floating point value to an integer value.
10341 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10342                                     SourceLocation CContext) {
10343   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10344   const bool PruneWarnings = S.inTemplateInstantiation();
10345 
10346   Expr *InnerE = E->IgnoreParenImpCasts();
10347   // We also want to warn on, e.g., "int i = -1.234"
10348   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10349     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10350       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10351 
10352   const bool IsLiteral =
10353       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10354 
10355   llvm::APFloat Value(0.0);
10356   bool IsConstant =
10357     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10358   if (!IsConstant) {
10359     return DiagnoseImpCast(S, E, T, CContext,
10360                            diag::warn_impcast_float_integer, PruneWarnings);
10361   }
10362 
10363   bool isExact = false;
10364 
10365   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10366                             T->hasUnsignedIntegerRepresentation());
10367   llvm::APFloat::opStatus Result = Value.convertToInteger(
10368       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10369 
10370   if (Result == llvm::APFloat::opOK && isExact) {
10371     if (IsLiteral) return;
10372     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10373                            PruneWarnings);
10374   }
10375 
10376   // Conversion of a floating-point value to a non-bool integer where the
10377   // integral part cannot be represented by the integer type is undefined.
10378   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10379     return DiagnoseImpCast(
10380         S, E, T, CContext,
10381         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10382                   : diag::warn_impcast_float_to_integer_out_of_range,
10383         PruneWarnings);
10384 
10385   unsigned DiagID = 0;
10386   if (IsLiteral) {
10387     // Warn on floating point literal to integer.
10388     DiagID = diag::warn_impcast_literal_float_to_integer;
10389   } else if (IntegerValue == 0) {
10390     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10391       return DiagnoseImpCast(S, E, T, CContext,
10392                              diag::warn_impcast_float_integer, PruneWarnings);
10393     }
10394     // Warn on non-zero to zero conversion.
10395     DiagID = diag::warn_impcast_float_to_integer_zero;
10396   } else {
10397     if (IntegerValue.isUnsigned()) {
10398       if (!IntegerValue.isMaxValue()) {
10399         return DiagnoseImpCast(S, E, T, CContext,
10400                                diag::warn_impcast_float_integer, PruneWarnings);
10401       }
10402     } else {  // IntegerValue.isSigned()
10403       if (!IntegerValue.isMaxSignedValue() &&
10404           !IntegerValue.isMinSignedValue()) {
10405         return DiagnoseImpCast(S, E, T, CContext,
10406                                diag::warn_impcast_float_integer, PruneWarnings);
10407       }
10408     }
10409     // Warn on evaluatable floating point expression to integer conversion.
10410     DiagID = diag::warn_impcast_float_to_integer;
10411   }
10412 
10413   // FIXME: Force the precision of the source value down so we don't print
10414   // digits which are usually useless (we don't really care here if we
10415   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10416   // would automatically print the shortest representation, but it's a bit
10417   // tricky to implement.
10418   SmallString<16> PrettySourceValue;
10419   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10420   precision = (precision * 59 + 195) / 196;
10421   Value.toString(PrettySourceValue, precision);
10422 
10423   SmallString<16> PrettyTargetValue;
10424   if (IsBool)
10425     PrettyTargetValue = Value.isZero() ? "false" : "true";
10426   else
10427     IntegerValue.toString(PrettyTargetValue);
10428 
10429   if (PruneWarnings) {
10430     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10431                           S.PDiag(DiagID)
10432                               << E->getType() << T.getUnqualifiedType()
10433                               << PrettySourceValue << PrettyTargetValue
10434                               << E->getSourceRange() << SourceRange(CContext));
10435   } else {
10436     S.Diag(E->getExprLoc(), DiagID)
10437         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10438         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10439   }
10440 }
10441 
10442 /// Analyze the given compound assignment for the possible losing of
10443 /// floating-point precision.
10444 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10445   assert(isa<CompoundAssignOperator>(E) &&
10446          "Must be compound assignment operation");
10447   // Recurse on the LHS and RHS in here
10448   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10449   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10450 
10451   if (E->getLHS()->getType()->isAtomicType())
10452     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10453 
10454   // Now check the outermost expression
10455   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10456   const auto *RBT = cast<CompoundAssignOperator>(E)
10457                         ->getComputationResultType()
10458                         ->getAs<BuiltinType>();
10459 
10460   // The below checks assume source is floating point.
10461   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10462 
10463   // If source is floating point but target is not.
10464   if (!ResultBT->isFloatingPoint())
10465     return DiagnoseFloatingImpCast(S, E, E->getRHS()->getType(),
10466                                    E->getExprLoc());
10467 
10468   // If both source and target are floating points.
10469   // Builtin FP kinds are ordered by increasing FP rank.
10470   if (ResultBT->getKind() < RBT->getKind() &&
10471       // We don't want to warn for system macro.
10472       !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10473     // warn about dropping FP rank.
10474     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10475                     diag::warn_impcast_float_result_precision);
10476 }
10477 
10478 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10479                                       IntRange Range) {
10480   if (!Range.Width) return "0";
10481 
10482   llvm::APSInt ValueInRange = Value;
10483   ValueInRange.setIsSigned(!Range.NonNegative);
10484   ValueInRange = ValueInRange.trunc(Range.Width);
10485   return ValueInRange.toString(10);
10486 }
10487 
10488 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10489   if (!isa<ImplicitCastExpr>(Ex))
10490     return false;
10491 
10492   Expr *InnerE = Ex->IgnoreParenImpCasts();
10493   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10494   const Type *Source =
10495     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10496   if (Target->isDependentType())
10497     return false;
10498 
10499   const BuiltinType *FloatCandidateBT =
10500     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10501   const Type *BoolCandidateType = ToBool ? Target : Source;
10502 
10503   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10504           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10505 }
10506 
10507 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10508                                              SourceLocation CC) {
10509   unsigned NumArgs = TheCall->getNumArgs();
10510   for (unsigned i = 0; i < NumArgs; ++i) {
10511     Expr *CurrA = TheCall->getArg(i);
10512     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10513       continue;
10514 
10515     bool IsSwapped = ((i > 0) &&
10516         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10517     IsSwapped |= ((i < (NumArgs - 1)) &&
10518         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10519     if (IsSwapped) {
10520       // Warn on this floating-point to bool conversion.
10521       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10522                       CurrA->getType(), CC,
10523                       diag::warn_impcast_floating_point_to_bool);
10524     }
10525   }
10526 }
10527 
10528 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10529                                    SourceLocation CC) {
10530   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10531                         E->getExprLoc()))
10532     return;
10533 
10534   // Don't warn on functions which have return type nullptr_t.
10535   if (isa<CallExpr>(E))
10536     return;
10537 
10538   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10539   const Expr::NullPointerConstantKind NullKind =
10540       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10541   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10542     return;
10543 
10544   // Return if target type is a safe conversion.
10545   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10546       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10547     return;
10548 
10549   SourceLocation Loc = E->getSourceRange().getBegin();
10550 
10551   // Venture through the macro stacks to get to the source of macro arguments.
10552   // The new location is a better location than the complete location that was
10553   // passed in.
10554   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10555   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10556 
10557   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10558   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10559     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10560         Loc, S.SourceMgr, S.getLangOpts());
10561     if (MacroName == "NULL")
10562       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10563   }
10564 
10565   // Only warn if the null and context location are in the same macro expansion.
10566   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10567     return;
10568 
10569   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10570       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10571       << FixItHint::CreateReplacement(Loc,
10572                                       S.getFixItZeroLiteralForType(T, Loc));
10573 }
10574 
10575 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10576                                   ObjCArrayLiteral *ArrayLiteral);
10577 
10578 static void
10579 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10580                            ObjCDictionaryLiteral *DictionaryLiteral);
10581 
10582 /// Check a single element within a collection literal against the
10583 /// target element type.
10584 static void checkObjCCollectionLiteralElement(Sema &S,
10585                                               QualType TargetElementType,
10586                                               Expr *Element,
10587                                               unsigned ElementKind) {
10588   // Skip a bitcast to 'id' or qualified 'id'.
10589   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10590     if (ICE->getCastKind() == CK_BitCast &&
10591         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10592       Element = ICE->getSubExpr();
10593   }
10594 
10595   QualType ElementType = Element->getType();
10596   ExprResult ElementResult(Element);
10597   if (ElementType->getAs<ObjCObjectPointerType>() &&
10598       S.CheckSingleAssignmentConstraints(TargetElementType,
10599                                          ElementResult,
10600                                          false, false)
10601         != Sema::Compatible) {
10602     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10603         << ElementType << ElementKind << TargetElementType
10604         << Element->getSourceRange();
10605   }
10606 
10607   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10608     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10609   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10610     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10611 }
10612 
10613 /// Check an Objective-C array literal being converted to the given
10614 /// target type.
10615 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10616                                   ObjCArrayLiteral *ArrayLiteral) {
10617   if (!S.NSArrayDecl)
10618     return;
10619 
10620   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10621   if (!TargetObjCPtr)
10622     return;
10623 
10624   if (TargetObjCPtr->isUnspecialized() ||
10625       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10626         != S.NSArrayDecl->getCanonicalDecl())
10627     return;
10628 
10629   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10630   if (TypeArgs.size() != 1)
10631     return;
10632 
10633   QualType TargetElementType = TypeArgs[0];
10634   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10635     checkObjCCollectionLiteralElement(S, TargetElementType,
10636                                       ArrayLiteral->getElement(I),
10637                                       0);
10638   }
10639 }
10640 
10641 /// Check an Objective-C dictionary literal being converted to the given
10642 /// target type.
10643 static void
10644 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10645                            ObjCDictionaryLiteral *DictionaryLiteral) {
10646   if (!S.NSDictionaryDecl)
10647     return;
10648 
10649   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10650   if (!TargetObjCPtr)
10651     return;
10652 
10653   if (TargetObjCPtr->isUnspecialized() ||
10654       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10655         != S.NSDictionaryDecl->getCanonicalDecl())
10656     return;
10657 
10658   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10659   if (TypeArgs.size() != 2)
10660     return;
10661 
10662   QualType TargetKeyType = TypeArgs[0];
10663   QualType TargetObjectType = TypeArgs[1];
10664   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10665     auto Element = DictionaryLiteral->getKeyValueElement(I);
10666     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10667     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10668   }
10669 }
10670 
10671 // Helper function to filter out cases for constant width constant conversion.
10672 // Don't warn on char array initialization or for non-decimal values.
10673 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10674                                           SourceLocation CC) {
10675   // If initializing from a constant, and the constant starts with '0',
10676   // then it is a binary, octal, or hexadecimal.  Allow these constants
10677   // to fill all the bits, even if there is a sign change.
10678   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10679     const char FirstLiteralCharacter =
10680         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10681     if (FirstLiteralCharacter == '0')
10682       return false;
10683   }
10684 
10685   // If the CC location points to a '{', and the type is char, then assume
10686   // assume it is an array initialization.
10687   if (CC.isValid() && T->isCharType()) {
10688     const char FirstContextCharacter =
10689         S.getSourceManager().getCharacterData(CC)[0];
10690     if (FirstContextCharacter == '{')
10691       return false;
10692   }
10693 
10694   return true;
10695 }
10696 
10697 static void
10698 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10699                         bool *ICContext = nullptr) {
10700   if (E->isTypeDependent() || E->isValueDependent()) return;
10701 
10702   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10703   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10704   if (Source == Target) return;
10705   if (Target->isDependentType()) return;
10706 
10707   // If the conversion context location is invalid don't complain. We also
10708   // don't want to emit a warning if the issue occurs from the expansion of
10709   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10710   // delay this check as long as possible. Once we detect we are in that
10711   // scenario, we just return.
10712   if (CC.isInvalid())
10713     return;
10714 
10715   if (Source->isAtomicType())
10716     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10717 
10718   // Diagnose implicit casts to bool.
10719   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10720     if (isa<StringLiteral>(E))
10721       // Warn on string literal to bool.  Checks for string literals in logical
10722       // and expressions, for instance, assert(0 && "error here"), are
10723       // prevented by a check in AnalyzeImplicitConversions().
10724       return DiagnoseImpCast(S, E, T, CC,
10725                              diag::warn_impcast_string_literal_to_bool);
10726     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10727         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10728       // This covers the literal expressions that evaluate to Objective-C
10729       // objects.
10730       return DiagnoseImpCast(S, E, T, CC,
10731                              diag::warn_impcast_objective_c_literal_to_bool);
10732     }
10733     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10734       // Warn on pointer to bool conversion that is always true.
10735       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10736                                      SourceRange(CC));
10737     }
10738   }
10739 
10740   // Check implicit casts from Objective-C collection literals to specialized
10741   // collection types, e.g., NSArray<NSString *> *.
10742   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10743     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10744   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10745     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10746 
10747   // Strip vector types.
10748   if (isa<VectorType>(Source)) {
10749     if (!isa<VectorType>(Target)) {
10750       if (S.SourceMgr.isInSystemMacro(CC))
10751         return;
10752       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10753     }
10754 
10755     // If the vector cast is cast between two vectors of the same size, it is
10756     // a bitcast, not a conversion.
10757     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10758       return;
10759 
10760     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10761     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10762   }
10763   if (auto VecTy = dyn_cast<VectorType>(Target))
10764     Target = VecTy->getElementType().getTypePtr();
10765 
10766   // Strip complex types.
10767   if (isa<ComplexType>(Source)) {
10768     if (!isa<ComplexType>(Target)) {
10769       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10770         return;
10771 
10772       return DiagnoseImpCast(S, E, T, CC,
10773                              S.getLangOpts().CPlusPlus
10774                                  ? diag::err_impcast_complex_scalar
10775                                  : diag::warn_impcast_complex_scalar);
10776     }
10777 
10778     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
10779     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
10780   }
10781 
10782   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
10783   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
10784 
10785   // If the source is floating point...
10786   if (SourceBT && SourceBT->isFloatingPoint()) {
10787     // ...and the target is floating point...
10788     if (TargetBT && TargetBT->isFloatingPoint()) {
10789       // ...then warn if we're dropping FP rank.
10790 
10791       // Builtin FP kinds are ordered by increasing FP rank.
10792       if (SourceBT->getKind() > TargetBT->getKind()) {
10793         // Don't warn about float constants that are precisely
10794         // representable in the target type.
10795         Expr::EvalResult result;
10796         if (E->EvaluateAsRValue(result, S.Context)) {
10797           // Value might be a float, a float vector, or a float complex.
10798           if (IsSameFloatAfterCast(result.Val,
10799                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
10800                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
10801             return;
10802         }
10803 
10804         if (S.SourceMgr.isInSystemMacro(CC))
10805           return;
10806 
10807         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
10808       }
10809       // ... or possibly if we're increasing rank, too
10810       else if (TargetBT->getKind() > SourceBT->getKind()) {
10811         if (S.SourceMgr.isInSystemMacro(CC))
10812           return;
10813 
10814         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
10815       }
10816       return;
10817     }
10818 
10819     // If the target is integral, always warn.
10820     if (TargetBT && TargetBT->isInteger()) {
10821       if (S.SourceMgr.isInSystemMacro(CC))
10822         return;
10823 
10824       DiagnoseFloatingImpCast(S, E, T, CC);
10825     }
10826 
10827     // Detect the case where a call result is converted from floating-point to
10828     // to bool, and the final argument to the call is converted from bool, to
10829     // discover this typo:
10830     //
10831     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
10832     //
10833     // FIXME: This is an incredibly special case; is there some more general
10834     // way to detect this class of misplaced-parentheses bug?
10835     if (Target->isBooleanType() && isa<CallExpr>(E)) {
10836       // Check last argument of function call to see if it is an
10837       // implicit cast from a type matching the type the result
10838       // is being cast to.
10839       CallExpr *CEx = cast<CallExpr>(E);
10840       if (unsigned NumArgs = CEx->getNumArgs()) {
10841         Expr *LastA = CEx->getArg(NumArgs - 1);
10842         Expr *InnerE = LastA->IgnoreParenImpCasts();
10843         if (isa<ImplicitCastExpr>(LastA) &&
10844             InnerE->getType()->isBooleanType()) {
10845           // Warn on this floating-point to bool conversion
10846           DiagnoseImpCast(S, E, T, CC,
10847                           diag::warn_impcast_floating_point_to_bool);
10848         }
10849       }
10850     }
10851     return;
10852   }
10853 
10854   DiagnoseNullConversion(S, E, T, CC);
10855 
10856   S.DiscardMisalignedMemberAddress(Target, E);
10857 
10858   if (!Source->isIntegerType() || !Target->isIntegerType())
10859     return;
10860 
10861   // TODO: remove this early return once the false positives for constant->bool
10862   // in templates, macros, etc, are reduced or removed.
10863   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
10864     return;
10865 
10866   IntRange SourceRange = GetExprRange(S.Context, E);
10867   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
10868 
10869   if (SourceRange.Width > TargetRange.Width) {
10870     // If the source is a constant, use a default-on diagnostic.
10871     // TODO: this should happen for bitfield stores, too.
10872     llvm::APSInt Value(32);
10873     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
10874       if (S.SourceMgr.isInSystemMacro(CC))
10875         return;
10876 
10877       std::string PrettySourceValue = Value.toString(10);
10878       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10879 
10880       S.DiagRuntimeBehavior(E->getExprLoc(), E,
10881         S.PDiag(diag::warn_impcast_integer_precision_constant)
10882             << PrettySourceValue << PrettyTargetValue
10883             << E->getType() << T << E->getSourceRange()
10884             << clang::SourceRange(CC));
10885       return;
10886     }
10887 
10888     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
10889     if (S.SourceMgr.isInSystemMacro(CC))
10890       return;
10891 
10892     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
10893       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
10894                              /* pruneControlFlow */ true);
10895     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
10896   }
10897 
10898   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
10899       SourceRange.NonNegative && Source->isSignedIntegerType()) {
10900     // Warn when doing a signed to signed conversion, warn if the positive
10901     // source value is exactly the width of the target type, which will
10902     // cause a negative value to be stored.
10903 
10904     llvm::APSInt Value;
10905     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
10906         !S.SourceMgr.isInSystemMacro(CC)) {
10907       if (isSameWidthConstantConversion(S, E, T, CC)) {
10908         std::string PrettySourceValue = Value.toString(10);
10909         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
10910 
10911         S.DiagRuntimeBehavior(
10912             E->getExprLoc(), E,
10913             S.PDiag(diag::warn_impcast_integer_precision_constant)
10914                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
10915                 << E->getSourceRange() << clang::SourceRange(CC));
10916         return;
10917       }
10918     }
10919 
10920     // Fall through for non-constants to give a sign conversion warning.
10921   }
10922 
10923   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
10924       (!TargetRange.NonNegative && SourceRange.NonNegative &&
10925        SourceRange.Width == TargetRange.Width)) {
10926     if (S.SourceMgr.isInSystemMacro(CC))
10927       return;
10928 
10929     unsigned DiagID = diag::warn_impcast_integer_sign;
10930 
10931     // Traditionally, gcc has warned about this under -Wsign-compare.
10932     // We also want to warn about it in -Wconversion.
10933     // So if -Wconversion is off, use a completely identical diagnostic
10934     // in the sign-compare group.
10935     // The conditional-checking code will
10936     if (ICContext) {
10937       DiagID = diag::warn_impcast_integer_sign_conditional;
10938       *ICContext = true;
10939     }
10940 
10941     return DiagnoseImpCast(S, E, T, CC, DiagID);
10942   }
10943 
10944   // Diagnose conversions between different enumeration types.
10945   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
10946   // type, to give us better diagnostics.
10947   QualType SourceType = E->getType();
10948   if (!S.getLangOpts().CPlusPlus) {
10949     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10950       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
10951         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
10952         SourceType = S.Context.getTypeDeclType(Enum);
10953         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
10954       }
10955   }
10956 
10957   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
10958     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
10959       if (SourceEnum->getDecl()->hasNameForLinkage() &&
10960           TargetEnum->getDecl()->hasNameForLinkage() &&
10961           SourceEnum != TargetEnum) {
10962         if (S.SourceMgr.isInSystemMacro(CC))
10963           return;
10964 
10965         return DiagnoseImpCast(S, E, SourceType, T, CC,
10966                                diag::warn_impcast_different_enum_types);
10967       }
10968 }
10969 
10970 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10971                                      SourceLocation CC, QualType T);
10972 
10973 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
10974                                     SourceLocation CC, bool &ICContext) {
10975   E = E->IgnoreParenImpCasts();
10976 
10977   if (isa<ConditionalOperator>(E))
10978     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
10979 
10980   AnalyzeImplicitConversions(S, E, CC);
10981   if (E->getType() != T)
10982     return CheckImplicitConversion(S, E, T, CC, &ICContext);
10983 }
10984 
10985 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
10986                                      SourceLocation CC, QualType T) {
10987   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
10988 
10989   bool Suspicious = false;
10990   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
10991   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
10992 
10993   // If -Wconversion would have warned about either of the candidates
10994   // for a signedness conversion to the context type...
10995   if (!Suspicious) return;
10996 
10997   // ...but it's currently ignored...
10998   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
10999     return;
11000 
11001   // ...then check whether it would have warned about either of the
11002   // candidates for a signedness conversion to the condition type.
11003   if (E->getType() == T) return;
11004 
11005   Suspicious = false;
11006   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11007                           E->getType(), CC, &Suspicious);
11008   if (!Suspicious)
11009     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11010                             E->getType(), CC, &Suspicious);
11011 }
11012 
11013 /// Check conversion of given expression to boolean.
11014 /// Input argument E is a logical expression.
11015 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11016   if (S.getLangOpts().Bool)
11017     return;
11018   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11019     return;
11020   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11021 }
11022 
11023 /// AnalyzeImplicitConversions - Find and report any interesting
11024 /// implicit conversions in the given expression.  There are a couple
11025 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11026 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11027                                        SourceLocation CC) {
11028   QualType T = OrigE->getType();
11029   Expr *E = OrigE->IgnoreParenImpCasts();
11030 
11031   if (E->isTypeDependent() || E->isValueDependent())
11032     return;
11033 
11034   // For conditional operators, we analyze the arguments as if they
11035   // were being fed directly into the output.
11036   if (isa<ConditionalOperator>(E)) {
11037     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11038     CheckConditionalOperator(S, CO, CC, T);
11039     return;
11040   }
11041 
11042   // Check implicit argument conversions for function calls.
11043   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11044     CheckImplicitArgumentConversions(S, Call, CC);
11045 
11046   // Go ahead and check any implicit conversions we might have skipped.
11047   // The non-canonical typecheck is just an optimization;
11048   // CheckImplicitConversion will filter out dead implicit conversions.
11049   if (E->getType() != T)
11050     CheckImplicitConversion(S, E, T, CC);
11051 
11052   // Now continue drilling into this expression.
11053 
11054   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11055     // The bound subexpressions in a PseudoObjectExpr are not reachable
11056     // as transitive children.
11057     // FIXME: Use a more uniform representation for this.
11058     for (auto *SE : POE->semantics())
11059       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11060         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11061   }
11062 
11063   // Skip past explicit casts.
11064   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11065     E = CE->getSubExpr()->IgnoreParenImpCasts();
11066     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11067       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11068     return AnalyzeImplicitConversions(S, E, CC);
11069   }
11070 
11071   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11072     // Do a somewhat different check with comparison operators.
11073     if (BO->isComparisonOp())
11074       return AnalyzeComparison(S, BO);
11075 
11076     // And with simple assignments.
11077     if (BO->getOpcode() == BO_Assign)
11078       return AnalyzeAssignment(S, BO);
11079     // And with compound assignments.
11080     if (BO->isAssignmentOp())
11081       return AnalyzeCompoundAssignment(S, BO);
11082   }
11083 
11084   // These break the otherwise-useful invariant below.  Fortunately,
11085   // we don't really need to recurse into them, because any internal
11086   // expressions should have been analyzed already when they were
11087   // built into statements.
11088   if (isa<StmtExpr>(E)) return;
11089 
11090   // Don't descend into unevaluated contexts.
11091   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11092 
11093   // Now just recurse over the expression's children.
11094   CC = E->getExprLoc();
11095   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11096   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11097   for (Stmt *SubStmt : E->children()) {
11098     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11099     if (!ChildExpr)
11100       continue;
11101 
11102     if (IsLogicalAndOperator &&
11103         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11104       // Ignore checking string literals that are in logical and operators.
11105       // This is a common pattern for asserts.
11106       continue;
11107     AnalyzeImplicitConversions(S, ChildExpr, CC);
11108   }
11109 
11110   if (BO && BO->isLogicalOp()) {
11111     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11112     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11113       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11114 
11115     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11116     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11117       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11118   }
11119 
11120   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11121     if (U->getOpcode() == UO_LNot) {
11122       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11123     } else if (U->getOpcode() != UO_AddrOf) {
11124       if (U->getSubExpr()->getType()->isAtomicType())
11125         S.Diag(U->getSubExpr()->getBeginLoc(),
11126                diag::warn_atomic_implicit_seq_cst);
11127     }
11128   }
11129 }
11130 
11131 /// Diagnose integer type and any valid implicit conversion to it.
11132 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11133   // Taking into account implicit conversions,
11134   // allow any integer.
11135   if (!E->getType()->isIntegerType()) {
11136     S.Diag(E->getBeginLoc(),
11137            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11138     return true;
11139   }
11140   // Potentially emit standard warnings for implicit conversions if enabled
11141   // using -Wconversion.
11142   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11143   return false;
11144 }
11145 
11146 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11147 // Returns true when emitting a warning about taking the address of a reference.
11148 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11149                               const PartialDiagnostic &PD) {
11150   E = E->IgnoreParenImpCasts();
11151 
11152   const FunctionDecl *FD = nullptr;
11153 
11154   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11155     if (!DRE->getDecl()->getType()->isReferenceType())
11156       return false;
11157   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11158     if (!M->getMemberDecl()->getType()->isReferenceType())
11159       return false;
11160   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11161     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11162       return false;
11163     FD = Call->getDirectCallee();
11164   } else {
11165     return false;
11166   }
11167 
11168   SemaRef.Diag(E->getExprLoc(), PD);
11169 
11170   // If possible, point to location of function.
11171   if (FD) {
11172     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11173   }
11174 
11175   return true;
11176 }
11177 
11178 // Returns true if the SourceLocation is expanded from any macro body.
11179 // Returns false if the SourceLocation is invalid, is from not in a macro
11180 // expansion, or is from expanded from a top-level macro argument.
11181 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11182   if (Loc.isInvalid())
11183     return false;
11184 
11185   while (Loc.isMacroID()) {
11186     if (SM.isMacroBodyExpansion(Loc))
11187       return true;
11188     Loc = SM.getImmediateMacroCallerLoc(Loc);
11189   }
11190 
11191   return false;
11192 }
11193 
11194 /// Diagnose pointers that are always non-null.
11195 /// \param E the expression containing the pointer
11196 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11197 /// compared to a null pointer
11198 /// \param IsEqual True when the comparison is equal to a null pointer
11199 /// \param Range Extra SourceRange to highlight in the diagnostic
11200 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11201                                         Expr::NullPointerConstantKind NullKind,
11202                                         bool IsEqual, SourceRange Range) {
11203   if (!E)
11204     return;
11205 
11206   // Don't warn inside macros.
11207   if (E->getExprLoc().isMacroID()) {
11208     const SourceManager &SM = getSourceManager();
11209     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11210         IsInAnyMacroBody(SM, Range.getBegin()))
11211       return;
11212   }
11213   E = E->IgnoreImpCasts();
11214 
11215   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11216 
11217   if (isa<CXXThisExpr>(E)) {
11218     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11219                                 : diag::warn_this_bool_conversion;
11220     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11221     return;
11222   }
11223 
11224   bool IsAddressOf = false;
11225 
11226   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11227     if (UO->getOpcode() != UO_AddrOf)
11228       return;
11229     IsAddressOf = true;
11230     E = UO->getSubExpr();
11231   }
11232 
11233   if (IsAddressOf) {
11234     unsigned DiagID = IsCompare
11235                           ? diag::warn_address_of_reference_null_compare
11236                           : diag::warn_address_of_reference_bool_conversion;
11237     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11238                                          << IsEqual;
11239     if (CheckForReference(*this, E, PD)) {
11240       return;
11241     }
11242   }
11243 
11244   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11245     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11246     std::string Str;
11247     llvm::raw_string_ostream S(Str);
11248     E->printPretty(S, nullptr, getPrintingPolicy());
11249     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11250                                 : diag::warn_cast_nonnull_to_bool;
11251     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11252       << E->getSourceRange() << Range << IsEqual;
11253     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11254   };
11255 
11256   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11257   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11258     if (auto *Callee = Call->getDirectCallee()) {
11259       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11260         ComplainAboutNonnullParamOrCall(A);
11261         return;
11262       }
11263     }
11264   }
11265 
11266   // Expect to find a single Decl.  Skip anything more complicated.
11267   ValueDecl *D = nullptr;
11268   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11269     D = R->getDecl();
11270   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11271     D = M->getMemberDecl();
11272   }
11273 
11274   // Weak Decls can be null.
11275   if (!D || D->isWeak())
11276     return;
11277 
11278   // Check for parameter decl with nonnull attribute
11279   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11280     if (getCurFunction() &&
11281         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11282       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11283         ComplainAboutNonnullParamOrCall(A);
11284         return;
11285       }
11286 
11287       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11288         auto ParamIter = llvm::find(FD->parameters(), PV);
11289         assert(ParamIter != FD->param_end());
11290         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11291 
11292         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11293           if (!NonNull->args_size()) {
11294               ComplainAboutNonnullParamOrCall(NonNull);
11295               return;
11296           }
11297 
11298           for (const ParamIdx &ArgNo : NonNull->args()) {
11299             if (ArgNo.getASTIndex() == ParamNo) {
11300               ComplainAboutNonnullParamOrCall(NonNull);
11301               return;
11302             }
11303           }
11304         }
11305       }
11306     }
11307   }
11308 
11309   QualType T = D->getType();
11310   const bool IsArray = T->isArrayType();
11311   const bool IsFunction = T->isFunctionType();
11312 
11313   // Address of function is used to silence the function warning.
11314   if (IsAddressOf && IsFunction) {
11315     return;
11316   }
11317 
11318   // Found nothing.
11319   if (!IsAddressOf && !IsFunction && !IsArray)
11320     return;
11321 
11322   // Pretty print the expression for the diagnostic.
11323   std::string Str;
11324   llvm::raw_string_ostream S(Str);
11325   E->printPretty(S, nullptr, getPrintingPolicy());
11326 
11327   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11328                               : diag::warn_impcast_pointer_to_bool;
11329   enum {
11330     AddressOf,
11331     FunctionPointer,
11332     ArrayPointer
11333   } DiagType;
11334   if (IsAddressOf)
11335     DiagType = AddressOf;
11336   else if (IsFunction)
11337     DiagType = FunctionPointer;
11338   else if (IsArray)
11339     DiagType = ArrayPointer;
11340   else
11341     llvm_unreachable("Could not determine diagnostic.");
11342   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11343                                 << Range << IsEqual;
11344 
11345   if (!IsFunction)
11346     return;
11347 
11348   // Suggest '&' to silence the function warning.
11349   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11350       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11351 
11352   // Check to see if '()' fixit should be emitted.
11353   QualType ReturnType;
11354   UnresolvedSet<4> NonTemplateOverloads;
11355   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11356   if (ReturnType.isNull())
11357     return;
11358 
11359   if (IsCompare) {
11360     // There are two cases here.  If there is null constant, the only suggest
11361     // for a pointer return type.  If the null is 0, then suggest if the return
11362     // type is a pointer or an integer type.
11363     if (!ReturnType->isPointerType()) {
11364       if (NullKind == Expr::NPCK_ZeroExpression ||
11365           NullKind == Expr::NPCK_ZeroLiteral) {
11366         if (!ReturnType->isIntegerType())
11367           return;
11368       } else {
11369         return;
11370       }
11371     }
11372   } else { // !IsCompare
11373     // For function to bool, only suggest if the function pointer has bool
11374     // return type.
11375     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11376       return;
11377   }
11378   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11379       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11380 }
11381 
11382 /// Diagnoses "dangerous" implicit conversions within the given
11383 /// expression (which is a full expression).  Implements -Wconversion
11384 /// and -Wsign-compare.
11385 ///
11386 /// \param CC the "context" location of the implicit conversion, i.e.
11387 ///   the most location of the syntactic entity requiring the implicit
11388 ///   conversion
11389 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11390   // Don't diagnose in unevaluated contexts.
11391   if (isUnevaluatedContext())
11392     return;
11393 
11394   // Don't diagnose for value- or type-dependent expressions.
11395   if (E->isTypeDependent() || E->isValueDependent())
11396     return;
11397 
11398   // Check for array bounds violations in cases where the check isn't triggered
11399   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11400   // ArraySubscriptExpr is on the RHS of a variable initialization.
11401   CheckArrayAccess(E);
11402 
11403   // This is not the right CC for (e.g.) a variable initialization.
11404   AnalyzeImplicitConversions(*this, E, CC);
11405 }
11406 
11407 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11408 /// Input argument E is a logical expression.
11409 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11410   ::CheckBoolLikeConversion(*this, E, CC);
11411 }
11412 
11413 /// Diagnose when expression is an integer constant expression and its evaluation
11414 /// results in integer overflow
11415 void Sema::CheckForIntOverflow (Expr *E) {
11416   // Use a work list to deal with nested struct initializers.
11417   SmallVector<Expr *, 2> Exprs(1, E);
11418 
11419   do {
11420     Expr *OriginalE = Exprs.pop_back_val();
11421     Expr *E = OriginalE->IgnoreParenCasts();
11422 
11423     if (isa<BinaryOperator>(E)) {
11424       E->EvaluateForOverflow(Context);
11425       continue;
11426     }
11427 
11428     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11429       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11430     else if (isa<ObjCBoxedExpr>(OriginalE))
11431       E->EvaluateForOverflow(Context);
11432     else if (auto Call = dyn_cast<CallExpr>(E))
11433       Exprs.append(Call->arg_begin(), Call->arg_end());
11434     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11435       Exprs.append(Message->arg_begin(), Message->arg_end());
11436   } while (!Exprs.empty());
11437 }
11438 
11439 namespace {
11440 
11441 /// Visitor for expressions which looks for unsequenced operations on the
11442 /// same object.
11443 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11444   using Base = EvaluatedExprVisitor<SequenceChecker>;
11445 
11446   /// A tree of sequenced regions within an expression. Two regions are
11447   /// unsequenced if one is an ancestor or a descendent of the other. When we
11448   /// finish processing an expression with sequencing, such as a comma
11449   /// expression, we fold its tree nodes into its parent, since they are
11450   /// unsequenced with respect to nodes we will visit later.
11451   class SequenceTree {
11452     struct Value {
11453       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11454       unsigned Parent : 31;
11455       unsigned Merged : 1;
11456     };
11457     SmallVector<Value, 8> Values;
11458 
11459   public:
11460     /// A region within an expression which may be sequenced with respect
11461     /// to some other region.
11462     class Seq {
11463       friend class SequenceTree;
11464 
11465       unsigned Index = 0;
11466 
11467       explicit Seq(unsigned N) : Index(N) {}
11468 
11469     public:
11470       Seq() = default;
11471     };
11472 
11473     SequenceTree() { Values.push_back(Value(0)); }
11474     Seq root() const { return Seq(0); }
11475 
11476     /// Create a new sequence of operations, which is an unsequenced
11477     /// subset of \p Parent. This sequence of operations is sequenced with
11478     /// respect to other children of \p Parent.
11479     Seq allocate(Seq Parent) {
11480       Values.push_back(Value(Parent.Index));
11481       return Seq(Values.size() - 1);
11482     }
11483 
11484     /// Merge a sequence of operations into its parent.
11485     void merge(Seq S) {
11486       Values[S.Index].Merged = true;
11487     }
11488 
11489     /// Determine whether two operations are unsequenced. This operation
11490     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11491     /// should have been merged into its parent as appropriate.
11492     bool isUnsequenced(Seq Cur, Seq Old) {
11493       unsigned C = representative(Cur.Index);
11494       unsigned Target = representative(Old.Index);
11495       while (C >= Target) {
11496         if (C == Target)
11497           return true;
11498         C = Values[C].Parent;
11499       }
11500       return false;
11501     }
11502 
11503   private:
11504     /// Pick a representative for a sequence.
11505     unsigned representative(unsigned K) {
11506       if (Values[K].Merged)
11507         // Perform path compression as we go.
11508         return Values[K].Parent = representative(Values[K].Parent);
11509       return K;
11510     }
11511   };
11512 
11513   /// An object for which we can track unsequenced uses.
11514   using Object = NamedDecl *;
11515 
11516   /// Different flavors of object usage which we track. We only track the
11517   /// least-sequenced usage of each kind.
11518   enum UsageKind {
11519     /// A read of an object. Multiple unsequenced reads are OK.
11520     UK_Use,
11521 
11522     /// A modification of an object which is sequenced before the value
11523     /// computation of the expression, such as ++n in C++.
11524     UK_ModAsValue,
11525 
11526     /// A modification of an object which is not sequenced before the value
11527     /// computation of the expression, such as n++.
11528     UK_ModAsSideEffect,
11529 
11530     UK_Count = UK_ModAsSideEffect + 1
11531   };
11532 
11533   struct Usage {
11534     Expr *Use = nullptr;
11535     SequenceTree::Seq Seq;
11536 
11537     Usage() = default;
11538   };
11539 
11540   struct UsageInfo {
11541     Usage Uses[UK_Count];
11542 
11543     /// Have we issued a diagnostic for this variable already?
11544     bool Diagnosed = false;
11545 
11546     UsageInfo() = default;
11547   };
11548   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11549 
11550   Sema &SemaRef;
11551 
11552   /// Sequenced regions within the expression.
11553   SequenceTree Tree;
11554 
11555   /// Declaration modifications and references which we have seen.
11556   UsageInfoMap UsageMap;
11557 
11558   /// The region we are currently within.
11559   SequenceTree::Seq Region;
11560 
11561   /// Filled in with declarations which were modified as a side-effect
11562   /// (that is, post-increment operations).
11563   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11564 
11565   /// Expressions to check later. We defer checking these to reduce
11566   /// stack usage.
11567   SmallVectorImpl<Expr *> &WorkList;
11568 
11569   /// RAII object wrapping the visitation of a sequenced subexpression of an
11570   /// expression. At the end of this process, the side-effects of the evaluation
11571   /// become sequenced with respect to the value computation of the result, so
11572   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11573   /// UK_ModAsValue.
11574   struct SequencedSubexpression {
11575     SequencedSubexpression(SequenceChecker &Self)
11576       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11577       Self.ModAsSideEffect = &ModAsSideEffect;
11578     }
11579 
11580     ~SequencedSubexpression() {
11581       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11582         UsageInfo &U = Self.UsageMap[M.first];
11583         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11584         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11585         SideEffectUsage = M.second;
11586       }
11587       Self.ModAsSideEffect = OldModAsSideEffect;
11588     }
11589 
11590     SequenceChecker &Self;
11591     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11592     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11593   };
11594 
11595   /// RAII object wrapping the visitation of a subexpression which we might
11596   /// choose to evaluate as a constant. If any subexpression is evaluated and
11597   /// found to be non-constant, this allows us to suppress the evaluation of
11598   /// the outer expression.
11599   class EvaluationTracker {
11600   public:
11601     EvaluationTracker(SequenceChecker &Self)
11602         : Self(Self), Prev(Self.EvalTracker) {
11603       Self.EvalTracker = this;
11604     }
11605 
11606     ~EvaluationTracker() {
11607       Self.EvalTracker = Prev;
11608       if (Prev)
11609         Prev->EvalOK &= EvalOK;
11610     }
11611 
11612     bool evaluate(const Expr *E, bool &Result) {
11613       if (!EvalOK || E->isValueDependent())
11614         return false;
11615       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11616       return EvalOK;
11617     }
11618 
11619   private:
11620     SequenceChecker &Self;
11621     EvaluationTracker *Prev;
11622     bool EvalOK = true;
11623   } *EvalTracker = nullptr;
11624 
11625   /// Find the object which is produced by the specified expression,
11626   /// if any.
11627   Object getObject(Expr *E, bool Mod) const {
11628     E = E->IgnoreParenCasts();
11629     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11630       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11631         return getObject(UO->getSubExpr(), Mod);
11632     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11633       if (BO->getOpcode() == BO_Comma)
11634         return getObject(BO->getRHS(), Mod);
11635       if (Mod && BO->isAssignmentOp())
11636         return getObject(BO->getLHS(), Mod);
11637     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11638       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11639       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11640         return ME->getMemberDecl();
11641     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11642       // FIXME: If this is a reference, map through to its value.
11643       return DRE->getDecl();
11644     return nullptr;
11645   }
11646 
11647   /// Note that an object was modified or used by an expression.
11648   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11649     Usage &U = UI.Uses[UK];
11650     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11651       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11652         ModAsSideEffect->push_back(std::make_pair(O, U));
11653       U.Use = Ref;
11654       U.Seq = Region;
11655     }
11656   }
11657 
11658   /// Check whether a modification or use conflicts with a prior usage.
11659   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11660                   bool IsModMod) {
11661     if (UI.Diagnosed)
11662       return;
11663 
11664     const Usage &U = UI.Uses[OtherKind];
11665     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11666       return;
11667 
11668     Expr *Mod = U.Use;
11669     Expr *ModOrUse = Ref;
11670     if (OtherKind == UK_Use)
11671       std::swap(Mod, ModOrUse);
11672 
11673     SemaRef.Diag(Mod->getExprLoc(),
11674                  IsModMod ? diag::warn_unsequenced_mod_mod
11675                           : diag::warn_unsequenced_mod_use)
11676       << O << SourceRange(ModOrUse->getExprLoc());
11677     UI.Diagnosed = true;
11678   }
11679 
11680   void notePreUse(Object O, Expr *Use) {
11681     UsageInfo &U = UsageMap[O];
11682     // Uses conflict with other modifications.
11683     checkUsage(O, U, Use, UK_ModAsValue, false);
11684   }
11685 
11686   void notePostUse(Object O, Expr *Use) {
11687     UsageInfo &U = UsageMap[O];
11688     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11689     addUsage(U, O, Use, UK_Use);
11690   }
11691 
11692   void notePreMod(Object O, Expr *Mod) {
11693     UsageInfo &U = UsageMap[O];
11694     // Modifications conflict with other modifications and with uses.
11695     checkUsage(O, U, Mod, UK_ModAsValue, true);
11696     checkUsage(O, U, Mod, UK_Use, false);
11697   }
11698 
11699   void notePostMod(Object O, Expr *Use, UsageKind UK) {
11700     UsageInfo &U = UsageMap[O];
11701     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
11702     addUsage(U, O, Use, UK);
11703   }
11704 
11705 public:
11706   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
11707       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
11708     Visit(E);
11709   }
11710 
11711   void VisitStmt(Stmt *S) {
11712     // Skip all statements which aren't expressions for now.
11713   }
11714 
11715   void VisitExpr(Expr *E) {
11716     // By default, just recurse to evaluated subexpressions.
11717     Base::VisitStmt(E);
11718   }
11719 
11720   void VisitCastExpr(CastExpr *E) {
11721     Object O = Object();
11722     if (E->getCastKind() == CK_LValueToRValue)
11723       O = getObject(E->getSubExpr(), false);
11724 
11725     if (O)
11726       notePreUse(O, E);
11727     VisitExpr(E);
11728     if (O)
11729       notePostUse(O, E);
11730   }
11731 
11732   void VisitBinComma(BinaryOperator *BO) {
11733     // C++11 [expr.comma]p1:
11734     //   Every value computation and side effect associated with the left
11735     //   expression is sequenced before every value computation and side
11736     //   effect associated with the right expression.
11737     SequenceTree::Seq LHS = Tree.allocate(Region);
11738     SequenceTree::Seq RHS = Tree.allocate(Region);
11739     SequenceTree::Seq OldRegion = Region;
11740 
11741     {
11742       SequencedSubexpression SeqLHS(*this);
11743       Region = LHS;
11744       Visit(BO->getLHS());
11745     }
11746 
11747     Region = RHS;
11748     Visit(BO->getRHS());
11749 
11750     Region = OldRegion;
11751 
11752     // Forget that LHS and RHS are sequenced. They are both unsequenced
11753     // with respect to other stuff.
11754     Tree.merge(LHS);
11755     Tree.merge(RHS);
11756   }
11757 
11758   void VisitBinAssign(BinaryOperator *BO) {
11759     // The modification is sequenced after the value computation of the LHS
11760     // and RHS, so check it before inspecting the operands and update the
11761     // map afterwards.
11762     Object O = getObject(BO->getLHS(), true);
11763     if (!O)
11764       return VisitExpr(BO);
11765 
11766     notePreMod(O, BO);
11767 
11768     // C++11 [expr.ass]p7:
11769     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
11770     //   only once.
11771     //
11772     // Therefore, for a compound assignment operator, O is considered used
11773     // everywhere except within the evaluation of E1 itself.
11774     if (isa<CompoundAssignOperator>(BO))
11775       notePreUse(O, BO);
11776 
11777     Visit(BO->getLHS());
11778 
11779     if (isa<CompoundAssignOperator>(BO))
11780       notePostUse(O, BO);
11781 
11782     Visit(BO->getRHS());
11783 
11784     // C++11 [expr.ass]p1:
11785     //   the assignment is sequenced [...] before the value computation of the
11786     //   assignment expression.
11787     // C11 6.5.16/3 has no such rule.
11788     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11789                                                        : UK_ModAsSideEffect);
11790   }
11791 
11792   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
11793     VisitBinAssign(CAO);
11794   }
11795 
11796   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11797   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
11798   void VisitUnaryPreIncDec(UnaryOperator *UO) {
11799     Object O = getObject(UO->getSubExpr(), true);
11800     if (!O)
11801       return VisitExpr(UO);
11802 
11803     notePreMod(O, UO);
11804     Visit(UO->getSubExpr());
11805     // C++11 [expr.pre.incr]p1:
11806     //   the expression ++x is equivalent to x+=1
11807     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
11808                                                        : UK_ModAsSideEffect);
11809   }
11810 
11811   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11812   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
11813   void VisitUnaryPostIncDec(UnaryOperator *UO) {
11814     Object O = getObject(UO->getSubExpr(), true);
11815     if (!O)
11816       return VisitExpr(UO);
11817 
11818     notePreMod(O, UO);
11819     Visit(UO->getSubExpr());
11820     notePostMod(O, UO, UK_ModAsSideEffect);
11821   }
11822 
11823   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
11824   void VisitBinLOr(BinaryOperator *BO) {
11825     // The side-effects of the LHS of an '&&' are sequenced before the
11826     // value computation of the RHS, and hence before the value computation
11827     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
11828     // as if they were unconditionally sequenced.
11829     EvaluationTracker Eval(*this);
11830     {
11831       SequencedSubexpression Sequenced(*this);
11832       Visit(BO->getLHS());
11833     }
11834 
11835     bool Result;
11836     if (Eval.evaluate(BO->getLHS(), Result)) {
11837       if (!Result)
11838         Visit(BO->getRHS());
11839     } else {
11840       // Check for unsequenced operations in the RHS, treating it as an
11841       // entirely separate evaluation.
11842       //
11843       // FIXME: If there are operations in the RHS which are unsequenced
11844       // with respect to operations outside the RHS, and those operations
11845       // are unconditionally evaluated, diagnose them.
11846       WorkList.push_back(BO->getRHS());
11847     }
11848   }
11849   void VisitBinLAnd(BinaryOperator *BO) {
11850     EvaluationTracker Eval(*this);
11851     {
11852       SequencedSubexpression Sequenced(*this);
11853       Visit(BO->getLHS());
11854     }
11855 
11856     bool Result;
11857     if (Eval.evaluate(BO->getLHS(), Result)) {
11858       if (Result)
11859         Visit(BO->getRHS());
11860     } else {
11861       WorkList.push_back(BO->getRHS());
11862     }
11863   }
11864 
11865   // Only visit the condition, unless we can be sure which subexpression will
11866   // be chosen.
11867   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
11868     EvaluationTracker Eval(*this);
11869     {
11870       SequencedSubexpression Sequenced(*this);
11871       Visit(CO->getCond());
11872     }
11873 
11874     bool Result;
11875     if (Eval.evaluate(CO->getCond(), Result))
11876       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
11877     else {
11878       WorkList.push_back(CO->getTrueExpr());
11879       WorkList.push_back(CO->getFalseExpr());
11880     }
11881   }
11882 
11883   void VisitCallExpr(CallExpr *CE) {
11884     // C++11 [intro.execution]p15:
11885     //   When calling a function [...], every value computation and side effect
11886     //   associated with any argument expression, or with the postfix expression
11887     //   designating the called function, is sequenced before execution of every
11888     //   expression or statement in the body of the function [and thus before
11889     //   the value computation of its result].
11890     SequencedSubexpression Sequenced(*this);
11891     Base::VisitCallExpr(CE);
11892 
11893     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
11894   }
11895 
11896   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
11897     // This is a call, so all subexpressions are sequenced before the result.
11898     SequencedSubexpression Sequenced(*this);
11899 
11900     if (!CCE->isListInitialization())
11901       return VisitExpr(CCE);
11902 
11903     // In C++11, list initializations are sequenced.
11904     SmallVector<SequenceTree::Seq, 32> Elts;
11905     SequenceTree::Seq Parent = Region;
11906     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
11907                                         E = CCE->arg_end();
11908          I != E; ++I) {
11909       Region = Tree.allocate(Parent);
11910       Elts.push_back(Region);
11911       Visit(*I);
11912     }
11913 
11914     // Forget that the initializers are sequenced.
11915     Region = Parent;
11916     for (unsigned I = 0; I < Elts.size(); ++I)
11917       Tree.merge(Elts[I]);
11918   }
11919 
11920   void VisitInitListExpr(InitListExpr *ILE) {
11921     if (!SemaRef.getLangOpts().CPlusPlus11)
11922       return VisitExpr(ILE);
11923 
11924     // In C++11, list initializations are sequenced.
11925     SmallVector<SequenceTree::Seq, 32> Elts;
11926     SequenceTree::Seq Parent = Region;
11927     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
11928       Expr *E = ILE->getInit(I);
11929       if (!E) continue;
11930       Region = Tree.allocate(Parent);
11931       Elts.push_back(Region);
11932       Visit(E);
11933     }
11934 
11935     // Forget that the initializers are sequenced.
11936     Region = Parent;
11937     for (unsigned I = 0; I < Elts.size(); ++I)
11938       Tree.merge(Elts[I]);
11939   }
11940 };
11941 
11942 } // namespace
11943 
11944 void Sema::CheckUnsequencedOperations(Expr *E) {
11945   SmallVector<Expr *, 8> WorkList;
11946   WorkList.push_back(E);
11947   while (!WorkList.empty()) {
11948     Expr *Item = WorkList.pop_back_val();
11949     SequenceChecker(*this, Item, WorkList);
11950   }
11951 }
11952 
11953 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
11954                               bool IsConstexpr) {
11955   CheckImplicitConversions(E, CheckLoc);
11956   if (!E->isInstantiationDependent())
11957     CheckUnsequencedOperations(E);
11958   if (!IsConstexpr && !E->isValueDependent())
11959     CheckForIntOverflow(E);
11960   DiagnoseMisalignedMembers();
11961 }
11962 
11963 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
11964                                        FieldDecl *BitField,
11965                                        Expr *Init) {
11966   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
11967 }
11968 
11969 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
11970                                          SourceLocation Loc) {
11971   if (!PType->isVariablyModifiedType())
11972     return;
11973   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
11974     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
11975     return;
11976   }
11977   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
11978     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
11979     return;
11980   }
11981   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
11982     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
11983     return;
11984   }
11985 
11986   const ArrayType *AT = S.Context.getAsArrayType(PType);
11987   if (!AT)
11988     return;
11989 
11990   if (AT->getSizeModifier() != ArrayType::Star) {
11991     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
11992     return;
11993   }
11994 
11995   S.Diag(Loc, diag::err_array_star_in_function_definition);
11996 }
11997 
11998 /// CheckParmsForFunctionDef - Check that the parameters of the given
11999 /// function are appropriate for the definition of a function. This
12000 /// takes care of any checks that cannot be performed on the
12001 /// declaration itself, e.g., that the types of each of the function
12002 /// parameters are complete.
12003 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12004                                     bool CheckParameterNames) {
12005   bool HasInvalidParm = false;
12006   for (ParmVarDecl *Param : Parameters) {
12007     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12008     // function declarator that is part of a function definition of
12009     // that function shall not have incomplete type.
12010     //
12011     // This is also C++ [dcl.fct]p6.
12012     if (!Param->isInvalidDecl() &&
12013         RequireCompleteType(Param->getLocation(), Param->getType(),
12014                             diag::err_typecheck_decl_incomplete_type)) {
12015       Param->setInvalidDecl();
12016       HasInvalidParm = true;
12017     }
12018 
12019     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12020     // declaration of each parameter shall include an identifier.
12021     if (CheckParameterNames &&
12022         Param->getIdentifier() == nullptr &&
12023         !Param->isImplicit() &&
12024         !getLangOpts().CPlusPlus)
12025       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12026 
12027     // C99 6.7.5.3p12:
12028     //   If the function declarator is not part of a definition of that
12029     //   function, parameters may have incomplete type and may use the [*]
12030     //   notation in their sequences of declarator specifiers to specify
12031     //   variable length array types.
12032     QualType PType = Param->getOriginalType();
12033     // FIXME: This diagnostic should point the '[*]' if source-location
12034     // information is added for it.
12035     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12036 
12037     // If the parameter is a c++ class type and it has to be destructed in the
12038     // callee function, declare the destructor so that it can be called by the
12039     // callee function. Do not perform any direct access check on the dtor here.
12040     if (!Param->isInvalidDecl()) {
12041       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12042         if (!ClassDecl->isInvalidDecl() &&
12043             !ClassDecl->hasIrrelevantDestructor() &&
12044             !ClassDecl->isDependentContext() &&
12045             ClassDecl->isParamDestroyedInCallee()) {
12046           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12047           MarkFunctionReferenced(Param->getLocation(), Destructor);
12048           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12049         }
12050       }
12051     }
12052 
12053     // Parameters with the pass_object_size attribute only need to be marked
12054     // constant at function definitions. Because we lack information about
12055     // whether we're on a declaration or definition when we're instantiating the
12056     // attribute, we need to check for constness here.
12057     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12058       if (!Param->getType().isConstQualified())
12059         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12060             << Attr->getSpelling() << 1;
12061   }
12062 
12063   return HasInvalidParm;
12064 }
12065 
12066 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12067 /// or MemberExpr.
12068 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12069                               ASTContext &Context) {
12070   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12071     return Context.getDeclAlign(DRE->getDecl());
12072 
12073   if (const auto *ME = dyn_cast<MemberExpr>(E))
12074     return Context.getDeclAlign(ME->getMemberDecl());
12075 
12076   return TypeAlign;
12077 }
12078 
12079 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12080 /// pointer cast increases the alignment requirements.
12081 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12082   // This is actually a lot of work to potentially be doing on every
12083   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12084   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12085     return;
12086 
12087   // Ignore dependent types.
12088   if (T->isDependentType() || Op->getType()->isDependentType())
12089     return;
12090 
12091   // Require that the destination be a pointer type.
12092   const PointerType *DestPtr = T->getAs<PointerType>();
12093   if (!DestPtr) return;
12094 
12095   // If the destination has alignment 1, we're done.
12096   QualType DestPointee = DestPtr->getPointeeType();
12097   if (DestPointee->isIncompleteType()) return;
12098   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12099   if (DestAlign.isOne()) return;
12100 
12101   // Require that the source be a pointer type.
12102   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12103   if (!SrcPtr) return;
12104   QualType SrcPointee = SrcPtr->getPointeeType();
12105 
12106   // Whitelist casts from cv void*.  We already implicitly
12107   // whitelisted casts to cv void*, since they have alignment 1.
12108   // Also whitelist casts involving incomplete types, which implicitly
12109   // includes 'void'.
12110   if (SrcPointee->isIncompleteType()) return;
12111 
12112   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12113 
12114   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12115     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12116       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12117   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12118     if (UO->getOpcode() == UO_AddrOf)
12119       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12120   }
12121 
12122   if (SrcAlign >= DestAlign) return;
12123 
12124   Diag(TRange.getBegin(), diag::warn_cast_align)
12125     << Op->getType() << T
12126     << static_cast<unsigned>(SrcAlign.getQuantity())
12127     << static_cast<unsigned>(DestAlign.getQuantity())
12128     << TRange << Op->getSourceRange();
12129 }
12130 
12131 /// Check whether this array fits the idiom of a size-one tail padded
12132 /// array member of a struct.
12133 ///
12134 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12135 /// commonly used to emulate flexible arrays in C89 code.
12136 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12137                                     const NamedDecl *ND) {
12138   if (Size != 1 || !ND) return false;
12139 
12140   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12141   if (!FD) return false;
12142 
12143   // Don't consider sizes resulting from macro expansions or template argument
12144   // substitution to form C89 tail-padded arrays.
12145 
12146   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12147   while (TInfo) {
12148     TypeLoc TL = TInfo->getTypeLoc();
12149     // Look through typedefs.
12150     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12151       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12152       TInfo = TDL->getTypeSourceInfo();
12153       continue;
12154     }
12155     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12156       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12157       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12158         return false;
12159     }
12160     break;
12161   }
12162 
12163   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12164   if (!RD) return false;
12165   if (RD->isUnion()) return false;
12166   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12167     if (!CRD->isStandardLayout()) return false;
12168   }
12169 
12170   // See if this is the last field decl in the record.
12171   const Decl *D = FD;
12172   while ((D = D->getNextDeclInContext()))
12173     if (isa<FieldDecl>(D))
12174       return false;
12175   return true;
12176 }
12177 
12178 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12179                             const ArraySubscriptExpr *ASE,
12180                             bool AllowOnePastEnd, bool IndexNegated) {
12181   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12182   if (IndexExpr->isValueDependent())
12183     return;
12184 
12185   const Type *EffectiveType =
12186       BaseExpr->getType()->getPointeeOrArrayElementType();
12187   BaseExpr = BaseExpr->IgnoreParenCasts();
12188   const ConstantArrayType *ArrayTy =
12189     Context.getAsConstantArrayType(BaseExpr->getType());
12190   if (!ArrayTy)
12191     return;
12192 
12193   llvm::APSInt index;
12194   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
12195     return;
12196   if (IndexNegated)
12197     index = -index;
12198 
12199   const NamedDecl *ND = nullptr;
12200   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12201     ND = DRE->getDecl();
12202   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12203     ND = ME->getMemberDecl();
12204 
12205   if (index.isUnsigned() || !index.isNegative()) {
12206     llvm::APInt size = ArrayTy->getSize();
12207     if (!size.isStrictlyPositive())
12208       return;
12209 
12210     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
12211     if (BaseType != EffectiveType) {
12212       // Make sure we're comparing apples to apples when comparing index to size
12213       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12214       uint64_t array_typesize = Context.getTypeSize(BaseType);
12215       // Handle ptrarith_typesize being zero, such as when casting to void*
12216       if (!ptrarith_typesize) ptrarith_typesize = 1;
12217       if (ptrarith_typesize != array_typesize) {
12218         // There's a cast to a different size type involved
12219         uint64_t ratio = array_typesize / ptrarith_typesize;
12220         // TODO: Be smarter about handling cases where array_typesize is not a
12221         // multiple of ptrarith_typesize
12222         if (ptrarith_typesize * ratio == array_typesize)
12223           size *= llvm::APInt(size.getBitWidth(), ratio);
12224       }
12225     }
12226 
12227     if (size.getBitWidth() > index.getBitWidth())
12228       index = index.zext(size.getBitWidth());
12229     else if (size.getBitWidth() < index.getBitWidth())
12230       size = size.zext(index.getBitWidth());
12231 
12232     // For array subscripting the index must be less than size, but for pointer
12233     // arithmetic also allow the index (offset) to be equal to size since
12234     // computing the next address after the end of the array is legal and
12235     // commonly done e.g. in C++ iterators and range-based for loops.
12236     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12237       return;
12238 
12239     // Also don't warn for arrays of size 1 which are members of some
12240     // structure. These are often used to approximate flexible arrays in C89
12241     // code.
12242     if (IsTailPaddedMemberArray(*this, size, ND))
12243       return;
12244 
12245     // Suppress the warning if the subscript expression (as identified by the
12246     // ']' location) and the index expression are both from macro expansions
12247     // within a system header.
12248     if (ASE) {
12249       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12250           ASE->getRBracketLoc());
12251       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12252         SourceLocation IndexLoc =
12253             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12254         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12255           return;
12256       }
12257     }
12258 
12259     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12260     if (ASE)
12261       DiagID = diag::warn_array_index_exceeds_bounds;
12262 
12263     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12264                         PDiag(DiagID) << index.toString(10, true)
12265                                       << size.toString(10, true)
12266                                       << (unsigned)size.getLimitedValue(~0U)
12267                                       << IndexExpr->getSourceRange());
12268   } else {
12269     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12270     if (!ASE) {
12271       DiagID = diag::warn_ptr_arith_precedes_bounds;
12272       if (index.isNegative()) index = -index;
12273     }
12274 
12275     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12276                         PDiag(DiagID) << index.toString(10, true)
12277                                       << IndexExpr->getSourceRange());
12278   }
12279 
12280   if (!ND) {
12281     // Try harder to find a NamedDecl to point at in the note.
12282     while (const ArraySubscriptExpr *ASE =
12283            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12284       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12285     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12286       ND = DRE->getDecl();
12287     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12288       ND = ME->getMemberDecl();
12289   }
12290 
12291   if (ND)
12292     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12293                         PDiag(diag::note_array_index_out_of_bounds)
12294                             << ND->getDeclName());
12295 }
12296 
12297 void Sema::CheckArrayAccess(const Expr *expr) {
12298   int AllowOnePastEnd = 0;
12299   while (expr) {
12300     expr = expr->IgnoreParenImpCasts();
12301     switch (expr->getStmtClass()) {
12302       case Stmt::ArraySubscriptExprClass: {
12303         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12304         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12305                          AllowOnePastEnd > 0);
12306         expr = ASE->getBase();
12307         break;
12308       }
12309       case Stmt::MemberExprClass: {
12310         expr = cast<MemberExpr>(expr)->getBase();
12311         break;
12312       }
12313       case Stmt::OMPArraySectionExprClass: {
12314         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12315         if (ASE->getLowerBound())
12316           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12317                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12318         return;
12319       }
12320       case Stmt::UnaryOperatorClass: {
12321         // Only unwrap the * and & unary operators
12322         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12323         expr = UO->getSubExpr();
12324         switch (UO->getOpcode()) {
12325           case UO_AddrOf:
12326             AllowOnePastEnd++;
12327             break;
12328           case UO_Deref:
12329             AllowOnePastEnd--;
12330             break;
12331           default:
12332             return;
12333         }
12334         break;
12335       }
12336       case Stmt::ConditionalOperatorClass: {
12337         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12338         if (const Expr *lhs = cond->getLHS())
12339           CheckArrayAccess(lhs);
12340         if (const Expr *rhs = cond->getRHS())
12341           CheckArrayAccess(rhs);
12342         return;
12343       }
12344       case Stmt::CXXOperatorCallExprClass: {
12345         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12346         for (const auto *Arg : OCE->arguments())
12347           CheckArrayAccess(Arg);
12348         return;
12349       }
12350       default:
12351         return;
12352     }
12353   }
12354 }
12355 
12356 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12357 
12358 namespace {
12359 
12360 struct RetainCycleOwner {
12361   VarDecl *Variable = nullptr;
12362   SourceRange Range;
12363   SourceLocation Loc;
12364   bool Indirect = false;
12365 
12366   RetainCycleOwner() = default;
12367 
12368   void setLocsFrom(Expr *e) {
12369     Loc = e->getExprLoc();
12370     Range = e->getSourceRange();
12371   }
12372 };
12373 
12374 } // namespace
12375 
12376 /// Consider whether capturing the given variable can possibly lead to
12377 /// a retain cycle.
12378 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12379   // In ARC, it's captured strongly iff the variable has __strong
12380   // lifetime.  In MRR, it's captured strongly if the variable is
12381   // __block and has an appropriate type.
12382   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12383     return false;
12384 
12385   owner.Variable = var;
12386   if (ref)
12387     owner.setLocsFrom(ref);
12388   return true;
12389 }
12390 
12391 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12392   while (true) {
12393     e = e->IgnoreParens();
12394     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12395       switch (cast->getCastKind()) {
12396       case CK_BitCast:
12397       case CK_LValueBitCast:
12398       case CK_LValueToRValue:
12399       case CK_ARCReclaimReturnedObject:
12400         e = cast->getSubExpr();
12401         continue;
12402 
12403       default:
12404         return false;
12405       }
12406     }
12407 
12408     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12409       ObjCIvarDecl *ivar = ref->getDecl();
12410       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12411         return false;
12412 
12413       // Try to find a retain cycle in the base.
12414       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12415         return false;
12416 
12417       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12418       owner.Indirect = true;
12419       return true;
12420     }
12421 
12422     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12423       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12424       if (!var) return false;
12425       return considerVariable(var, ref, owner);
12426     }
12427 
12428     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12429       if (member->isArrow()) return false;
12430 
12431       // Don't count this as an indirect ownership.
12432       e = member->getBase();
12433       continue;
12434     }
12435 
12436     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12437       // Only pay attention to pseudo-objects on property references.
12438       ObjCPropertyRefExpr *pre
12439         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12440                                               ->IgnoreParens());
12441       if (!pre) return false;
12442       if (pre->isImplicitProperty()) return false;
12443       ObjCPropertyDecl *property = pre->getExplicitProperty();
12444       if (!property->isRetaining() &&
12445           !(property->getPropertyIvarDecl() &&
12446             property->getPropertyIvarDecl()->getType()
12447               .getObjCLifetime() == Qualifiers::OCL_Strong))
12448           return false;
12449 
12450       owner.Indirect = true;
12451       if (pre->isSuperReceiver()) {
12452         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12453         if (!owner.Variable)
12454           return false;
12455         owner.Loc = pre->getLocation();
12456         owner.Range = pre->getSourceRange();
12457         return true;
12458       }
12459       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12460                               ->getSourceExpr());
12461       continue;
12462     }
12463 
12464     // Array ivars?
12465 
12466     return false;
12467   }
12468 }
12469 
12470 namespace {
12471 
12472   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12473     ASTContext &Context;
12474     VarDecl *Variable;
12475     Expr *Capturer = nullptr;
12476     bool VarWillBeReased = false;
12477 
12478     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12479         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12480           Context(Context), Variable(variable) {}
12481 
12482     void VisitDeclRefExpr(DeclRefExpr *ref) {
12483       if (ref->getDecl() == Variable && !Capturer)
12484         Capturer = ref;
12485     }
12486 
12487     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12488       if (Capturer) return;
12489       Visit(ref->getBase());
12490       if (Capturer && ref->isFreeIvar())
12491         Capturer = ref;
12492     }
12493 
12494     void VisitBlockExpr(BlockExpr *block) {
12495       // Look inside nested blocks
12496       if (block->getBlockDecl()->capturesVariable(Variable))
12497         Visit(block->getBlockDecl()->getBody());
12498     }
12499 
12500     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12501       if (Capturer) return;
12502       if (OVE->getSourceExpr())
12503         Visit(OVE->getSourceExpr());
12504     }
12505 
12506     void VisitBinaryOperator(BinaryOperator *BinOp) {
12507       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12508         return;
12509       Expr *LHS = BinOp->getLHS();
12510       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12511         if (DRE->getDecl() != Variable)
12512           return;
12513         if (Expr *RHS = BinOp->getRHS()) {
12514           RHS = RHS->IgnoreParenCasts();
12515           llvm::APSInt Value;
12516           VarWillBeReased =
12517             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12518         }
12519       }
12520     }
12521   };
12522 
12523 } // namespace
12524 
12525 /// Check whether the given argument is a block which captures a
12526 /// variable.
12527 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12528   assert(owner.Variable && owner.Loc.isValid());
12529 
12530   e = e->IgnoreParenCasts();
12531 
12532   // Look through [^{...} copy] and Block_copy(^{...}).
12533   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12534     Selector Cmd = ME->getSelector();
12535     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12536       e = ME->getInstanceReceiver();
12537       if (!e)
12538         return nullptr;
12539       e = e->IgnoreParenCasts();
12540     }
12541   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12542     if (CE->getNumArgs() == 1) {
12543       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12544       if (Fn) {
12545         const IdentifierInfo *FnI = Fn->getIdentifier();
12546         if (FnI && FnI->isStr("_Block_copy")) {
12547           e = CE->getArg(0)->IgnoreParenCasts();
12548         }
12549       }
12550     }
12551   }
12552 
12553   BlockExpr *block = dyn_cast<BlockExpr>(e);
12554   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12555     return nullptr;
12556 
12557   FindCaptureVisitor visitor(S.Context, owner.Variable);
12558   visitor.Visit(block->getBlockDecl()->getBody());
12559   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12560 }
12561 
12562 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12563                                 RetainCycleOwner &owner) {
12564   assert(capturer);
12565   assert(owner.Variable && owner.Loc.isValid());
12566 
12567   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12568     << owner.Variable << capturer->getSourceRange();
12569   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12570     << owner.Indirect << owner.Range;
12571 }
12572 
12573 /// Check for a keyword selector that starts with the word 'add' or
12574 /// 'set'.
12575 static bool isSetterLikeSelector(Selector sel) {
12576   if (sel.isUnarySelector()) return false;
12577 
12578   StringRef str = sel.getNameForSlot(0);
12579   while (!str.empty() && str.front() == '_') str = str.substr(1);
12580   if (str.startswith("set"))
12581     str = str.substr(3);
12582   else if (str.startswith("add")) {
12583     // Specially whitelist 'addOperationWithBlock:'.
12584     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12585       return false;
12586     str = str.substr(3);
12587   }
12588   else
12589     return false;
12590 
12591   if (str.empty()) return true;
12592   return !isLowercase(str.front());
12593 }
12594 
12595 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12596                                                     ObjCMessageExpr *Message) {
12597   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12598                                                 Message->getReceiverInterface(),
12599                                                 NSAPI::ClassId_NSMutableArray);
12600   if (!IsMutableArray) {
12601     return None;
12602   }
12603 
12604   Selector Sel = Message->getSelector();
12605 
12606   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12607     S.NSAPIObj->getNSArrayMethodKind(Sel);
12608   if (!MKOpt) {
12609     return None;
12610   }
12611 
12612   NSAPI::NSArrayMethodKind MK = *MKOpt;
12613 
12614   switch (MK) {
12615     case NSAPI::NSMutableArr_addObject:
12616     case NSAPI::NSMutableArr_insertObjectAtIndex:
12617     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12618       return 0;
12619     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12620       return 1;
12621 
12622     default:
12623       return None;
12624   }
12625 
12626   return None;
12627 }
12628 
12629 static
12630 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12631                                                   ObjCMessageExpr *Message) {
12632   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12633                                             Message->getReceiverInterface(),
12634                                             NSAPI::ClassId_NSMutableDictionary);
12635   if (!IsMutableDictionary) {
12636     return None;
12637   }
12638 
12639   Selector Sel = Message->getSelector();
12640 
12641   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12642     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12643   if (!MKOpt) {
12644     return None;
12645   }
12646 
12647   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12648 
12649   switch (MK) {
12650     case NSAPI::NSMutableDict_setObjectForKey:
12651     case NSAPI::NSMutableDict_setValueForKey:
12652     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12653       return 0;
12654 
12655     default:
12656       return None;
12657   }
12658 
12659   return None;
12660 }
12661 
12662 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
12663   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
12664                                                 Message->getReceiverInterface(),
12665                                                 NSAPI::ClassId_NSMutableSet);
12666 
12667   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
12668                                             Message->getReceiverInterface(),
12669                                             NSAPI::ClassId_NSMutableOrderedSet);
12670   if (!IsMutableSet && !IsMutableOrderedSet) {
12671     return None;
12672   }
12673 
12674   Selector Sel = Message->getSelector();
12675 
12676   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
12677   if (!MKOpt) {
12678     return None;
12679   }
12680 
12681   NSAPI::NSSetMethodKind MK = *MKOpt;
12682 
12683   switch (MK) {
12684     case NSAPI::NSMutableSet_addObject:
12685     case NSAPI::NSOrderedSet_setObjectAtIndex:
12686     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
12687     case NSAPI::NSOrderedSet_insertObjectAtIndex:
12688       return 0;
12689     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
12690       return 1;
12691   }
12692 
12693   return None;
12694 }
12695 
12696 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
12697   if (!Message->isInstanceMessage()) {
12698     return;
12699   }
12700 
12701   Optional<int> ArgOpt;
12702 
12703   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
12704       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
12705       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
12706     return;
12707   }
12708 
12709   int ArgIndex = *ArgOpt;
12710 
12711   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
12712   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
12713     Arg = OE->getSourceExpr()->IgnoreImpCasts();
12714   }
12715 
12716   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
12717     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12718       if (ArgRE->isObjCSelfExpr()) {
12719         Diag(Message->getSourceRange().getBegin(),
12720              diag::warn_objc_circular_container)
12721           << ArgRE->getDecl() << StringRef("'super'");
12722       }
12723     }
12724   } else {
12725     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
12726 
12727     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
12728       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
12729     }
12730 
12731     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
12732       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
12733         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
12734           ValueDecl *Decl = ReceiverRE->getDecl();
12735           Diag(Message->getSourceRange().getBegin(),
12736                diag::warn_objc_circular_container)
12737             << Decl << Decl;
12738           if (!ArgRE->isObjCSelfExpr()) {
12739             Diag(Decl->getLocation(),
12740                  diag::note_objc_circular_container_declared_here)
12741               << Decl;
12742           }
12743         }
12744       }
12745     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
12746       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
12747         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
12748           ObjCIvarDecl *Decl = IvarRE->getDecl();
12749           Diag(Message->getSourceRange().getBegin(),
12750                diag::warn_objc_circular_container)
12751             << Decl << Decl;
12752           Diag(Decl->getLocation(),
12753                diag::note_objc_circular_container_declared_here)
12754             << Decl;
12755         }
12756       }
12757     }
12758   }
12759 }
12760 
12761 /// Check a message send to see if it's likely to cause a retain cycle.
12762 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
12763   // Only check instance methods whose selector looks like a setter.
12764   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
12765     return;
12766 
12767   // Try to find a variable that the receiver is strongly owned by.
12768   RetainCycleOwner owner;
12769   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
12770     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
12771       return;
12772   } else {
12773     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
12774     owner.Variable = getCurMethodDecl()->getSelfDecl();
12775     owner.Loc = msg->getSuperLoc();
12776     owner.Range = msg->getSuperLoc();
12777   }
12778 
12779   // Check whether the receiver is captured by any of the arguments.
12780   const ObjCMethodDecl *MD = msg->getMethodDecl();
12781   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
12782     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
12783       // noescape blocks should not be retained by the method.
12784       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
12785         continue;
12786       return diagnoseRetainCycle(*this, capturer, owner);
12787     }
12788   }
12789 }
12790 
12791 /// Check a property assign to see if it's likely to cause a retain cycle.
12792 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
12793   RetainCycleOwner owner;
12794   if (!findRetainCycleOwner(*this, receiver, owner))
12795     return;
12796 
12797   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
12798     diagnoseRetainCycle(*this, capturer, owner);
12799 }
12800 
12801 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
12802   RetainCycleOwner Owner;
12803   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
12804     return;
12805 
12806   // Because we don't have an expression for the variable, we have to set the
12807   // location explicitly here.
12808   Owner.Loc = Var->getLocation();
12809   Owner.Range = Var->getSourceRange();
12810 
12811   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
12812     diagnoseRetainCycle(*this, Capturer, Owner);
12813 }
12814 
12815 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
12816                                      Expr *RHS, bool isProperty) {
12817   // Check if RHS is an Objective-C object literal, which also can get
12818   // immediately zapped in a weak reference.  Note that we explicitly
12819   // allow ObjCStringLiterals, since those are designed to never really die.
12820   RHS = RHS->IgnoreParenImpCasts();
12821 
12822   // This enum needs to match with the 'select' in
12823   // warn_objc_arc_literal_assign (off-by-1).
12824   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
12825   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
12826     return false;
12827 
12828   S.Diag(Loc, diag::warn_arc_literal_assign)
12829     << (unsigned) Kind
12830     << (isProperty ? 0 : 1)
12831     << RHS->getSourceRange();
12832 
12833   return true;
12834 }
12835 
12836 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
12837                                     Qualifiers::ObjCLifetime LT,
12838                                     Expr *RHS, bool isProperty) {
12839   // Strip off any implicit cast added to get to the one ARC-specific.
12840   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12841     if (cast->getCastKind() == CK_ARCConsumeObject) {
12842       S.Diag(Loc, diag::warn_arc_retained_assign)
12843         << (LT == Qualifiers::OCL_ExplicitNone)
12844         << (isProperty ? 0 : 1)
12845         << RHS->getSourceRange();
12846       return true;
12847     }
12848     RHS = cast->getSubExpr();
12849   }
12850 
12851   if (LT == Qualifiers::OCL_Weak &&
12852       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
12853     return true;
12854 
12855   return false;
12856 }
12857 
12858 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
12859                               QualType LHS, Expr *RHS) {
12860   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
12861 
12862   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
12863     return false;
12864 
12865   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
12866     return true;
12867 
12868   return false;
12869 }
12870 
12871 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
12872                               Expr *LHS, Expr *RHS) {
12873   QualType LHSType;
12874   // PropertyRef on LHS type need be directly obtained from
12875   // its declaration as it has a PseudoType.
12876   ObjCPropertyRefExpr *PRE
12877     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
12878   if (PRE && !PRE->isImplicitProperty()) {
12879     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12880     if (PD)
12881       LHSType = PD->getType();
12882   }
12883 
12884   if (LHSType.isNull())
12885     LHSType = LHS->getType();
12886 
12887   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
12888 
12889   if (LT == Qualifiers::OCL_Weak) {
12890     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
12891       getCurFunction()->markSafeWeakUse(LHS);
12892   }
12893 
12894   if (checkUnsafeAssigns(Loc, LHSType, RHS))
12895     return;
12896 
12897   // FIXME. Check for other life times.
12898   if (LT != Qualifiers::OCL_None)
12899     return;
12900 
12901   if (PRE) {
12902     if (PRE->isImplicitProperty())
12903       return;
12904     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
12905     if (!PD)
12906       return;
12907 
12908     unsigned Attributes = PD->getPropertyAttributes();
12909     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
12910       // when 'assign' attribute was not explicitly specified
12911       // by user, ignore it and rely on property type itself
12912       // for lifetime info.
12913       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
12914       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
12915           LHSType->isObjCRetainableType())
12916         return;
12917 
12918       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
12919         if (cast->getCastKind() == CK_ARCConsumeObject) {
12920           Diag(Loc, diag::warn_arc_retained_property_assign)
12921           << RHS->getSourceRange();
12922           return;
12923         }
12924         RHS = cast->getSubExpr();
12925       }
12926     }
12927     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
12928       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
12929         return;
12930     }
12931   }
12932 }
12933 
12934 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
12935 
12936 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
12937                                         SourceLocation StmtLoc,
12938                                         const NullStmt *Body) {
12939   // Do not warn if the body is a macro that expands to nothing, e.g:
12940   //
12941   // #define CALL(x)
12942   // if (condition)
12943   //   CALL(0);
12944   if (Body->hasLeadingEmptyMacro())
12945     return false;
12946 
12947   // Get line numbers of statement and body.
12948   bool StmtLineInvalid;
12949   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
12950                                                       &StmtLineInvalid);
12951   if (StmtLineInvalid)
12952     return false;
12953 
12954   bool BodyLineInvalid;
12955   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
12956                                                       &BodyLineInvalid);
12957   if (BodyLineInvalid)
12958     return false;
12959 
12960   // Warn if null statement and body are on the same line.
12961   if (StmtLine != BodyLine)
12962     return false;
12963 
12964   return true;
12965 }
12966 
12967 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
12968                                  const Stmt *Body,
12969                                  unsigned DiagID) {
12970   // Since this is a syntactic check, don't emit diagnostic for template
12971   // instantiations, this just adds noise.
12972   if (CurrentInstantiationScope)
12973     return;
12974 
12975   // The body should be a null statement.
12976   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
12977   if (!NBody)
12978     return;
12979 
12980   // Do the usual checks.
12981   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
12982     return;
12983 
12984   Diag(NBody->getSemiLoc(), DiagID);
12985   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
12986 }
12987 
12988 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
12989                                  const Stmt *PossibleBody) {
12990   assert(!CurrentInstantiationScope); // Ensured by caller
12991 
12992   SourceLocation StmtLoc;
12993   const Stmt *Body;
12994   unsigned DiagID;
12995   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
12996     StmtLoc = FS->getRParenLoc();
12997     Body = FS->getBody();
12998     DiagID = diag::warn_empty_for_body;
12999   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13000     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13001     Body = WS->getBody();
13002     DiagID = diag::warn_empty_while_body;
13003   } else
13004     return; // Neither `for' nor `while'.
13005 
13006   // The body should be a null statement.
13007   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13008   if (!NBody)
13009     return;
13010 
13011   // Skip expensive checks if diagnostic is disabled.
13012   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13013     return;
13014 
13015   // Do the usual checks.
13016   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13017     return;
13018 
13019   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13020   // noise level low, emit diagnostics only if for/while is followed by a
13021   // CompoundStmt, e.g.:
13022   //    for (int i = 0; i < n; i++);
13023   //    {
13024   //      a(i);
13025   //    }
13026   // or if for/while is followed by a statement with more indentation
13027   // than for/while itself:
13028   //    for (int i = 0; i < n; i++);
13029   //      a(i);
13030   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13031   if (!ProbableTypo) {
13032     bool BodyColInvalid;
13033     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13034         PossibleBody->getBeginLoc(), &BodyColInvalid);
13035     if (BodyColInvalid)
13036       return;
13037 
13038     bool StmtColInvalid;
13039     unsigned StmtCol =
13040         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13041     if (StmtColInvalid)
13042       return;
13043 
13044     if (BodyCol > StmtCol)
13045       ProbableTypo = true;
13046   }
13047 
13048   if (ProbableTypo) {
13049     Diag(NBody->getSemiLoc(), DiagID);
13050     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13051   }
13052 }
13053 
13054 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13055 
13056 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13057 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13058                              SourceLocation OpLoc) {
13059   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13060     return;
13061 
13062   if (inTemplateInstantiation())
13063     return;
13064 
13065   // Strip parens and casts away.
13066   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13067   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13068 
13069   // Check for a call expression
13070   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13071   if (!CE || CE->getNumArgs() != 1)
13072     return;
13073 
13074   // Check for a call to std::move
13075   if (!CE->isCallToStdMove())
13076     return;
13077 
13078   // Get argument from std::move
13079   RHSExpr = CE->getArg(0);
13080 
13081   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13082   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13083 
13084   // Two DeclRefExpr's, check that the decls are the same.
13085   if (LHSDeclRef && RHSDeclRef) {
13086     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13087       return;
13088     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13089         RHSDeclRef->getDecl()->getCanonicalDecl())
13090       return;
13091 
13092     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13093                                         << LHSExpr->getSourceRange()
13094                                         << RHSExpr->getSourceRange();
13095     return;
13096   }
13097 
13098   // Member variables require a different approach to check for self moves.
13099   // MemberExpr's are the same if every nested MemberExpr refers to the same
13100   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13101   // the base Expr's are CXXThisExpr's.
13102   const Expr *LHSBase = LHSExpr;
13103   const Expr *RHSBase = RHSExpr;
13104   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13105   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13106   if (!LHSME || !RHSME)
13107     return;
13108 
13109   while (LHSME && RHSME) {
13110     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13111         RHSME->getMemberDecl()->getCanonicalDecl())
13112       return;
13113 
13114     LHSBase = LHSME->getBase();
13115     RHSBase = RHSME->getBase();
13116     LHSME = dyn_cast<MemberExpr>(LHSBase);
13117     RHSME = dyn_cast<MemberExpr>(RHSBase);
13118   }
13119 
13120   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13121   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13122   if (LHSDeclRef && RHSDeclRef) {
13123     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13124       return;
13125     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13126         RHSDeclRef->getDecl()->getCanonicalDecl())
13127       return;
13128 
13129     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13130                                         << LHSExpr->getSourceRange()
13131                                         << RHSExpr->getSourceRange();
13132     return;
13133   }
13134 
13135   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13136     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13137                                         << LHSExpr->getSourceRange()
13138                                         << RHSExpr->getSourceRange();
13139 }
13140 
13141 //===--- Layout compatibility ----------------------------------------------//
13142 
13143 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13144 
13145 /// Check if two enumeration types are layout-compatible.
13146 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13147   // C++11 [dcl.enum] p8:
13148   // Two enumeration types are layout-compatible if they have the same
13149   // underlying type.
13150   return ED1->isComplete() && ED2->isComplete() &&
13151          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13152 }
13153 
13154 /// Check if two fields are layout-compatible.
13155 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13156                                FieldDecl *Field2) {
13157   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13158     return false;
13159 
13160   if (Field1->isBitField() != Field2->isBitField())
13161     return false;
13162 
13163   if (Field1->isBitField()) {
13164     // Make sure that the bit-fields are the same length.
13165     unsigned Bits1 = Field1->getBitWidthValue(C);
13166     unsigned Bits2 = Field2->getBitWidthValue(C);
13167 
13168     if (Bits1 != Bits2)
13169       return false;
13170   }
13171 
13172   return true;
13173 }
13174 
13175 /// Check if two standard-layout structs are layout-compatible.
13176 /// (C++11 [class.mem] p17)
13177 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13178                                      RecordDecl *RD2) {
13179   // If both records are C++ classes, check that base classes match.
13180   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13181     // If one of records is a CXXRecordDecl we are in C++ mode,
13182     // thus the other one is a CXXRecordDecl, too.
13183     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13184     // Check number of base classes.
13185     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13186       return false;
13187 
13188     // Check the base classes.
13189     for (CXXRecordDecl::base_class_const_iterator
13190                Base1 = D1CXX->bases_begin(),
13191            BaseEnd1 = D1CXX->bases_end(),
13192               Base2 = D2CXX->bases_begin();
13193          Base1 != BaseEnd1;
13194          ++Base1, ++Base2) {
13195       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13196         return false;
13197     }
13198   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13199     // If only RD2 is a C++ class, it should have zero base classes.
13200     if (D2CXX->getNumBases() > 0)
13201       return false;
13202   }
13203 
13204   // Check the fields.
13205   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13206                              Field2End = RD2->field_end(),
13207                              Field1 = RD1->field_begin(),
13208                              Field1End = RD1->field_end();
13209   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13210     if (!isLayoutCompatible(C, *Field1, *Field2))
13211       return false;
13212   }
13213   if (Field1 != Field1End || Field2 != Field2End)
13214     return false;
13215 
13216   return true;
13217 }
13218 
13219 /// Check if two standard-layout unions are layout-compatible.
13220 /// (C++11 [class.mem] p18)
13221 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13222                                     RecordDecl *RD2) {
13223   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13224   for (auto *Field2 : RD2->fields())
13225     UnmatchedFields.insert(Field2);
13226 
13227   for (auto *Field1 : RD1->fields()) {
13228     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13229         I = UnmatchedFields.begin(),
13230         E = UnmatchedFields.end();
13231 
13232     for ( ; I != E; ++I) {
13233       if (isLayoutCompatible(C, Field1, *I)) {
13234         bool Result = UnmatchedFields.erase(*I);
13235         (void) Result;
13236         assert(Result);
13237         break;
13238       }
13239     }
13240     if (I == E)
13241       return false;
13242   }
13243 
13244   return UnmatchedFields.empty();
13245 }
13246 
13247 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13248                                RecordDecl *RD2) {
13249   if (RD1->isUnion() != RD2->isUnion())
13250     return false;
13251 
13252   if (RD1->isUnion())
13253     return isLayoutCompatibleUnion(C, RD1, RD2);
13254   else
13255     return isLayoutCompatibleStruct(C, RD1, RD2);
13256 }
13257 
13258 /// Check if two types are layout-compatible in C++11 sense.
13259 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13260   if (T1.isNull() || T2.isNull())
13261     return false;
13262 
13263   // C++11 [basic.types] p11:
13264   // If two types T1 and T2 are the same type, then T1 and T2 are
13265   // layout-compatible types.
13266   if (C.hasSameType(T1, T2))
13267     return true;
13268 
13269   T1 = T1.getCanonicalType().getUnqualifiedType();
13270   T2 = T2.getCanonicalType().getUnqualifiedType();
13271 
13272   const Type::TypeClass TC1 = T1->getTypeClass();
13273   const Type::TypeClass TC2 = T2->getTypeClass();
13274 
13275   if (TC1 != TC2)
13276     return false;
13277 
13278   if (TC1 == Type::Enum) {
13279     return isLayoutCompatible(C,
13280                               cast<EnumType>(T1)->getDecl(),
13281                               cast<EnumType>(T2)->getDecl());
13282   } else if (TC1 == Type::Record) {
13283     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13284       return false;
13285 
13286     return isLayoutCompatible(C,
13287                               cast<RecordType>(T1)->getDecl(),
13288                               cast<RecordType>(T2)->getDecl());
13289   }
13290 
13291   return false;
13292 }
13293 
13294 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13295 
13296 /// Given a type tag expression find the type tag itself.
13297 ///
13298 /// \param TypeExpr Type tag expression, as it appears in user's code.
13299 ///
13300 /// \param VD Declaration of an identifier that appears in a type tag.
13301 ///
13302 /// \param MagicValue Type tag magic value.
13303 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13304                             const ValueDecl **VD, uint64_t *MagicValue) {
13305   while(true) {
13306     if (!TypeExpr)
13307       return false;
13308 
13309     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13310 
13311     switch (TypeExpr->getStmtClass()) {
13312     case Stmt::UnaryOperatorClass: {
13313       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13314       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13315         TypeExpr = UO->getSubExpr();
13316         continue;
13317       }
13318       return false;
13319     }
13320 
13321     case Stmt::DeclRefExprClass: {
13322       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13323       *VD = DRE->getDecl();
13324       return true;
13325     }
13326 
13327     case Stmt::IntegerLiteralClass: {
13328       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13329       llvm::APInt MagicValueAPInt = IL->getValue();
13330       if (MagicValueAPInt.getActiveBits() <= 64) {
13331         *MagicValue = MagicValueAPInt.getZExtValue();
13332         return true;
13333       } else
13334         return false;
13335     }
13336 
13337     case Stmt::BinaryConditionalOperatorClass:
13338     case Stmt::ConditionalOperatorClass: {
13339       const AbstractConditionalOperator *ACO =
13340           cast<AbstractConditionalOperator>(TypeExpr);
13341       bool Result;
13342       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13343         if (Result)
13344           TypeExpr = ACO->getTrueExpr();
13345         else
13346           TypeExpr = ACO->getFalseExpr();
13347         continue;
13348       }
13349       return false;
13350     }
13351 
13352     case Stmt::BinaryOperatorClass: {
13353       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13354       if (BO->getOpcode() == BO_Comma) {
13355         TypeExpr = BO->getRHS();
13356         continue;
13357       }
13358       return false;
13359     }
13360 
13361     default:
13362       return false;
13363     }
13364   }
13365 }
13366 
13367 /// Retrieve the C type corresponding to type tag TypeExpr.
13368 ///
13369 /// \param TypeExpr Expression that specifies a type tag.
13370 ///
13371 /// \param MagicValues Registered magic values.
13372 ///
13373 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13374 ///        kind.
13375 ///
13376 /// \param TypeInfo Information about the corresponding C type.
13377 ///
13378 /// \returns true if the corresponding C type was found.
13379 static bool GetMatchingCType(
13380         const IdentifierInfo *ArgumentKind,
13381         const Expr *TypeExpr, const ASTContext &Ctx,
13382         const llvm::DenseMap<Sema::TypeTagMagicValue,
13383                              Sema::TypeTagData> *MagicValues,
13384         bool &FoundWrongKind,
13385         Sema::TypeTagData &TypeInfo) {
13386   FoundWrongKind = false;
13387 
13388   // Variable declaration that has type_tag_for_datatype attribute.
13389   const ValueDecl *VD = nullptr;
13390 
13391   uint64_t MagicValue;
13392 
13393   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13394     return false;
13395 
13396   if (VD) {
13397     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13398       if (I->getArgumentKind() != ArgumentKind) {
13399         FoundWrongKind = true;
13400         return false;
13401       }
13402       TypeInfo.Type = I->getMatchingCType();
13403       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13404       TypeInfo.MustBeNull = I->getMustBeNull();
13405       return true;
13406     }
13407     return false;
13408   }
13409 
13410   if (!MagicValues)
13411     return false;
13412 
13413   llvm::DenseMap<Sema::TypeTagMagicValue,
13414                  Sema::TypeTagData>::const_iterator I =
13415       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13416   if (I == MagicValues->end())
13417     return false;
13418 
13419   TypeInfo = I->second;
13420   return true;
13421 }
13422 
13423 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13424                                       uint64_t MagicValue, QualType Type,
13425                                       bool LayoutCompatible,
13426                                       bool MustBeNull) {
13427   if (!TypeTagForDatatypeMagicValues)
13428     TypeTagForDatatypeMagicValues.reset(
13429         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13430 
13431   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13432   (*TypeTagForDatatypeMagicValues)[Magic] =
13433       TypeTagData(Type, LayoutCompatible, MustBeNull);
13434 }
13435 
13436 static bool IsSameCharType(QualType T1, QualType T2) {
13437   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13438   if (!BT1)
13439     return false;
13440 
13441   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13442   if (!BT2)
13443     return false;
13444 
13445   BuiltinType::Kind T1Kind = BT1->getKind();
13446   BuiltinType::Kind T2Kind = BT2->getKind();
13447 
13448   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13449          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13450          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13451          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13452 }
13453 
13454 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13455                                     const ArrayRef<const Expr *> ExprArgs,
13456                                     SourceLocation CallSiteLoc) {
13457   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13458   bool IsPointerAttr = Attr->getIsPointer();
13459 
13460   // Retrieve the argument representing the 'type_tag'.
13461   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13462   if (TypeTagIdxAST >= ExprArgs.size()) {
13463     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13464         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13465     return;
13466   }
13467   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13468   bool FoundWrongKind;
13469   TypeTagData TypeInfo;
13470   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13471                         TypeTagForDatatypeMagicValues.get(),
13472                         FoundWrongKind, TypeInfo)) {
13473     if (FoundWrongKind)
13474       Diag(TypeTagExpr->getExprLoc(),
13475            diag::warn_type_tag_for_datatype_wrong_kind)
13476         << TypeTagExpr->getSourceRange();
13477     return;
13478   }
13479 
13480   // Retrieve the argument representing the 'arg_idx'.
13481   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13482   if (ArgumentIdxAST >= ExprArgs.size()) {
13483     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13484         << 1 << Attr->getArgumentIdx().getSourceIndex();
13485     return;
13486   }
13487   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13488   if (IsPointerAttr) {
13489     // Skip implicit cast of pointer to `void *' (as a function argument).
13490     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13491       if (ICE->getType()->isVoidPointerType() &&
13492           ICE->getCastKind() == CK_BitCast)
13493         ArgumentExpr = ICE->getSubExpr();
13494   }
13495   QualType ArgumentType = ArgumentExpr->getType();
13496 
13497   // Passing a `void*' pointer shouldn't trigger a warning.
13498   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13499     return;
13500 
13501   if (TypeInfo.MustBeNull) {
13502     // Type tag with matching void type requires a null pointer.
13503     if (!ArgumentExpr->isNullPointerConstant(Context,
13504                                              Expr::NPC_ValueDependentIsNotNull)) {
13505       Diag(ArgumentExpr->getExprLoc(),
13506            diag::warn_type_safety_null_pointer_required)
13507           << ArgumentKind->getName()
13508           << ArgumentExpr->getSourceRange()
13509           << TypeTagExpr->getSourceRange();
13510     }
13511     return;
13512   }
13513 
13514   QualType RequiredType = TypeInfo.Type;
13515   if (IsPointerAttr)
13516     RequiredType = Context.getPointerType(RequiredType);
13517 
13518   bool mismatch = false;
13519   if (!TypeInfo.LayoutCompatible) {
13520     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13521 
13522     // C++11 [basic.fundamental] p1:
13523     // Plain char, signed char, and unsigned char are three distinct types.
13524     //
13525     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13526     // char' depending on the current char signedness mode.
13527     if (mismatch)
13528       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13529                                            RequiredType->getPointeeType())) ||
13530           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13531         mismatch = false;
13532   } else
13533     if (IsPointerAttr)
13534       mismatch = !isLayoutCompatible(Context,
13535                                      ArgumentType->getPointeeType(),
13536                                      RequiredType->getPointeeType());
13537     else
13538       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13539 
13540   if (mismatch)
13541     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13542         << ArgumentType << ArgumentKind
13543         << TypeInfo.LayoutCompatible << RequiredType
13544         << ArgumentExpr->getSourceRange()
13545         << TypeTagExpr->getSourceRange();
13546 }
13547 
13548 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13549                                          CharUnits Alignment) {
13550   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13551 }
13552 
13553 void Sema::DiagnoseMisalignedMembers() {
13554   for (MisalignedMember &m : MisalignedMembers) {
13555     const NamedDecl *ND = m.RD;
13556     if (ND->getName().empty()) {
13557       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13558         ND = TD;
13559     }
13560     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13561         << m.MD << ND << m.E->getSourceRange();
13562   }
13563   MisalignedMembers.clear();
13564 }
13565 
13566 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13567   E = E->IgnoreParens();
13568   if (!T->isPointerType() && !T->isIntegerType())
13569     return;
13570   if (isa<UnaryOperator>(E) &&
13571       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13572     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13573     if (isa<MemberExpr>(Op)) {
13574       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13575                           MisalignedMember(Op));
13576       if (MA != MisalignedMembers.end() &&
13577           (T->isIntegerType() ||
13578            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13579                                    Context.getTypeAlignInChars(
13580                                        T->getPointeeType()) <= MA->Alignment))))
13581         MisalignedMembers.erase(MA);
13582     }
13583   }
13584 }
13585 
13586 void Sema::RefersToMemberWithReducedAlignment(
13587     Expr *E,
13588     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13589         Action) {
13590   const auto *ME = dyn_cast<MemberExpr>(E);
13591   if (!ME)
13592     return;
13593 
13594   // No need to check expressions with an __unaligned-qualified type.
13595   if (E->getType().getQualifiers().hasUnaligned())
13596     return;
13597 
13598   // For a chain of MemberExpr like "a.b.c.d" this list
13599   // will keep FieldDecl's like [d, c, b].
13600   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13601   const MemberExpr *TopME = nullptr;
13602   bool AnyIsPacked = false;
13603   do {
13604     QualType BaseType = ME->getBase()->getType();
13605     if (ME->isArrow())
13606       BaseType = BaseType->getPointeeType();
13607     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13608     if (RD->isInvalidDecl())
13609       return;
13610 
13611     ValueDecl *MD = ME->getMemberDecl();
13612     auto *FD = dyn_cast<FieldDecl>(MD);
13613     // We do not care about non-data members.
13614     if (!FD || FD->isInvalidDecl())
13615       return;
13616 
13617     AnyIsPacked =
13618         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13619     ReverseMemberChain.push_back(FD);
13620 
13621     TopME = ME;
13622     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13623   } while (ME);
13624   assert(TopME && "We did not compute a topmost MemberExpr!");
13625 
13626   // Not the scope of this diagnostic.
13627   if (!AnyIsPacked)
13628     return;
13629 
13630   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13631   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13632   // TODO: The innermost base of the member expression may be too complicated.
13633   // For now, just disregard these cases. This is left for future
13634   // improvement.
13635   if (!DRE && !isa<CXXThisExpr>(TopBase))
13636       return;
13637 
13638   // Alignment expected by the whole expression.
13639   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13640 
13641   // No need to do anything else with this case.
13642   if (ExpectedAlignment.isOne())
13643     return;
13644 
13645   // Synthesize offset of the whole access.
13646   CharUnits Offset;
13647   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13648        I++) {
13649     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13650   }
13651 
13652   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13653   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13654       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13655 
13656   // The base expression of the innermost MemberExpr may give
13657   // stronger guarantees than the class containing the member.
13658   if (DRE && !TopME->isArrow()) {
13659     const ValueDecl *VD = DRE->getDecl();
13660     if (!VD->getType()->isReferenceType())
13661       CompleteObjectAlignment =
13662           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
13663   }
13664 
13665   // Check if the synthesized offset fulfills the alignment.
13666   if (Offset % ExpectedAlignment != 0 ||
13667       // It may fulfill the offset it but the effective alignment may still be
13668       // lower than the expected expression alignment.
13669       CompleteObjectAlignment < ExpectedAlignment) {
13670     // If this happens, we want to determine a sensible culprit of this.
13671     // Intuitively, watching the chain of member expressions from right to
13672     // left, we start with the required alignment (as required by the field
13673     // type) but some packed attribute in that chain has reduced the alignment.
13674     // It may happen that another packed structure increases it again. But if
13675     // we are here such increase has not been enough. So pointing the first
13676     // FieldDecl that either is packed or else its RecordDecl is,
13677     // seems reasonable.
13678     FieldDecl *FD = nullptr;
13679     CharUnits Alignment;
13680     for (FieldDecl *FDI : ReverseMemberChain) {
13681       if (FDI->hasAttr<PackedAttr>() ||
13682           FDI->getParent()->hasAttr<PackedAttr>()) {
13683         FD = FDI;
13684         Alignment = std::min(
13685             Context.getTypeAlignInChars(FD->getType()),
13686             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
13687         break;
13688       }
13689     }
13690     assert(FD && "We did not find a packed FieldDecl!");
13691     Action(E, FD->getParent(), FD, Alignment);
13692   }
13693 }
13694 
13695 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
13696   using namespace std::placeholders;
13697 
13698   RefersToMemberWithReducedAlignment(
13699       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
13700                      _2, _3, _4));
13701 }
13702