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/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
43 
44 using namespace clang;
45 using namespace sema;
46 
47 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
48                                                     unsigned ByteNo) const {
49   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
50                                Context.getTargetInfo());
51 }
52 
53 /// Checks that a call expression's argument count is the desired number.
54 /// This is useful when doing custom type-checking.  Returns true on error.
55 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
56   unsigned argCount = call->getNumArgs();
57   if (argCount == desiredArgCount) return false;
58 
59   if (argCount < desiredArgCount)
60     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
61         << 0 /*function call*/ << desiredArgCount << argCount
62         << call->getSourceRange();
63 
64   // Highlight all the excess arguments.
65   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
66                     call->getArg(argCount - 1)->getLocEnd());
67 
68   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69     << 0 /*function call*/ << desiredArgCount << argCount
70     << call->getArg(1)->getSourceRange();
71 }
72 
73 /// Check that the first argument to __builtin_annotation is an integer
74 /// and the second argument is a non-wide string literal.
75 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
76   if (checkArgCount(S, TheCall, 2))
77     return true;
78 
79   // First argument should be an integer.
80   Expr *ValArg = TheCall->getArg(0);
81   QualType Ty = ValArg->getType();
82   if (!Ty->isIntegerType()) {
83     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
84       << ValArg->getSourceRange();
85     return true;
86   }
87 
88   // Second argument should be a constant string.
89   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
90   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
91   if (!Literal || !Literal->isAscii()) {
92     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
93       << StrArg->getSourceRange();
94     return true;
95   }
96 
97   TheCall->setType(Ty);
98   return false;
99 }
100 
101 /// Check that the argument to __builtin_addressof is a glvalue, and set the
102 /// result type to the corresponding pointer type.
103 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
104   if (checkArgCount(S, TheCall, 1))
105     return true;
106 
107   ExprResult Arg(TheCall->getArg(0));
108   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
109   if (ResultType.isNull())
110     return true;
111 
112   TheCall->setArg(0, Arg.get());
113   TheCall->setType(ResultType);
114   return false;
115 }
116 
117 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
118   if (checkArgCount(S, TheCall, 3))
119     return true;
120 
121   // First two arguments should be integers.
122   for (unsigned I = 0; I < 2; ++I) {
123     Expr *Arg = TheCall->getArg(I);
124     QualType Ty = Arg->getType();
125     if (!Ty->isIntegerType()) {
126       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
127           << Ty << Arg->getSourceRange();
128       return true;
129     }
130   }
131 
132   // Third argument should be a pointer to a non-const integer.
133   // IRGen correctly handles volatile, restrict, and address spaces, and
134   // the other qualifiers aren't possible.
135   {
136     Expr *Arg = TheCall->getArg(2);
137     QualType Ty = Arg->getType();
138     const auto *PtrTy = Ty->getAs<PointerType>();
139     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140           !PtrTy->getPointeeType().isConstQualified())) {
141       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
142           << Ty << Arg->getSourceRange();
143       return true;
144     }
145   }
146 
147   return false;
148 }
149 
150 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
151 		                  CallExpr *TheCall, unsigned SizeIdx,
152                                   unsigned DstSizeIdx) {
153   if (TheCall->getNumArgs() <= SizeIdx ||
154       TheCall->getNumArgs() <= DstSizeIdx)
155     return;
156 
157   const Expr *SizeArg = TheCall->getArg(SizeIdx);
158   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
159 
160   llvm::APSInt Size, DstSize;
161 
162   // find out if both sizes are known at compile time
163   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
164       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
165     return;
166 
167   if (Size.ule(DstSize))
168     return;
169 
170   // confirmed overflow so generate the diagnostic.
171   IdentifierInfo *FnName = FDecl->getIdentifier();
172   SourceLocation SL = TheCall->getLocStart();
173   SourceRange SR = TheCall->getSourceRange();
174 
175   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
176 }
177 
178 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
179   if (checkArgCount(S, BuiltinCall, 2))
180     return true;
181 
182   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
183   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
184   Expr *Call = BuiltinCall->getArg(0);
185   Expr *Chain = BuiltinCall->getArg(1);
186 
187   if (Call->getStmtClass() != Stmt::CallExprClass) {
188     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
189         << Call->getSourceRange();
190     return true;
191   }
192 
193   auto CE = cast<CallExpr>(Call);
194   if (CE->getCallee()->getType()->isBlockPointerType()) {
195     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
196         << Call->getSourceRange();
197     return true;
198   }
199 
200   const Decl *TargetDecl = CE->getCalleeDecl();
201   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202     if (FD->getBuiltinID()) {
203       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
204           << Call->getSourceRange();
205       return true;
206     }
207 
208   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
210         << Call->getSourceRange();
211     return true;
212   }
213 
214   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
215   if (ChainResult.isInvalid())
216     return true;
217   if (!ChainResult.get()->getType()->isPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
219         << Chain->getSourceRange();
220     return true;
221   }
222 
223   QualType ReturnTy = CE->getCallReturnType(S.Context);
224   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
225   QualType BuiltinTy = S.Context.getFunctionType(
226       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
227   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
228 
229   Builtin =
230       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
231 
232   BuiltinCall->setType(CE->getType());
233   BuiltinCall->setValueKind(CE->getValueKind());
234   BuiltinCall->setObjectKind(CE->getObjectKind());
235   BuiltinCall->setCallee(Builtin);
236   BuiltinCall->setArg(1, ChainResult.get());
237 
238   return false;
239 }
240 
241 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
242                                      Scope::ScopeFlags NeededScopeFlags,
243                                      unsigned DiagID) {
244   // Scopes aren't available during instantiation. Fortunately, builtin
245   // functions cannot be template args so they cannot be formed through template
246   // instantiation. Therefore checking once during the parse is sufficient.
247   if (!SemaRef.ActiveTemplateInstantiations.empty())
248     return false;
249 
250   Scope *S = SemaRef.getCurScope();
251   while (S && !S->isSEHExceptScope())
252     S = S->getParent();
253   if (!S || !(S->getFlags() & NeededScopeFlags)) {
254     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
255     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
256         << DRE->getDecl()->getIdentifier();
257     return true;
258   }
259 
260   return false;
261 }
262 
263 static inline bool isBlockPointer(Expr *Arg) {
264   return Arg->getType()->isBlockPointerType();
265 }
266 
267 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
268 /// void*, which is a requirement of device side enqueue.
269 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
270   const BlockPointerType *BPT =
271       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
272   ArrayRef<QualType> Params =
273       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
274   unsigned ArgCounter = 0;
275   bool IllegalParams = false;
276   // Iterate through the block parameters until either one is found that is not
277   // a local void*, or the block is valid.
278   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
279        I != E; ++I, ++ArgCounter) {
280     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
282             LangAS::opencl_local) {
283       // Get the location of the error. If a block literal has been passed
284       // (BlockExpr) then we can point straight to the offending argument,
285       // else we just point to the variable reference.
286       SourceLocation ErrorLoc;
287       if (isa<BlockExpr>(BlockArg)) {
288         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
289         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
290       } else if (isa<DeclRefExpr>(BlockArg)) {
291         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
292       }
293       S.Diag(ErrorLoc,
294              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295       IllegalParams = true;
296     }
297   }
298 
299   return IllegalParams;
300 }
301 
302 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
303 /// get_kernel_work_group_size
304 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
305 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
306   if (checkArgCount(S, TheCall, 1))
307     return true;
308 
309   Expr *BlockArg = TheCall->getArg(0);
310   if (!isBlockPointer(BlockArg)) {
311     S.Diag(BlockArg->getLocStart(),
312            diag::err_opencl_enqueue_kernel_expected_type) << "block";
313     return true;
314   }
315   return checkOpenCLBlockArgs(S, BlockArg);
316 }
317 
318 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
319                                             unsigned Start, unsigned End);
320 
321 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
322 /// 'local void*' parameter of passed block.
323 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
324                                            Expr *BlockArg,
325                                            unsigned NumNonVarArgs) {
326   const BlockPointerType *BPT =
327       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
328   unsigned NumBlockParams =
329       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
330   unsigned TotalNumArgs = TheCall->getNumArgs();
331 
332   // For each argument passed to the block, a corresponding uint needs to
333   // be passed to describe the size of the local memory.
334   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
335     S.Diag(TheCall->getLocStart(),
336            diag::err_opencl_enqueue_kernel_local_size_args);
337     return true;
338   }
339 
340   // Check that the sizes of the local memory are specified by integers.
341   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
342                                          TotalNumArgs - 1);
343 }
344 
345 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
346 /// overload formats specified in Table 6.13.17.1.
347 /// int enqueue_kernel(queue_t queue,
348 ///                    kernel_enqueue_flags_t flags,
349 ///                    const ndrange_t ndrange,
350 ///                    void (^block)(void))
351 /// int enqueue_kernel(queue_t queue,
352 ///                    kernel_enqueue_flags_t flags,
353 ///                    const ndrange_t ndrange,
354 ///                    uint num_events_in_wait_list,
355 ///                    clk_event_t *event_wait_list,
356 ///                    clk_event_t *event_ret,
357 ///                    void (^block)(void))
358 /// int enqueue_kernel(queue_t queue,
359 ///                    kernel_enqueue_flags_t flags,
360 ///                    const ndrange_t ndrange,
361 ///                    void (^block)(local void*, ...),
362 ///                    uint size0, ...)
363 /// int enqueue_kernel(queue_t queue,
364 ///                    kernel_enqueue_flags_t flags,
365 ///                    const ndrange_t ndrange,
366 ///                    uint num_events_in_wait_list,
367 ///                    clk_event_t *event_wait_list,
368 ///                    clk_event_t *event_ret,
369 ///                    void (^block)(local void*, ...),
370 ///                    uint size0, ...)
371 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
372   unsigned NumArgs = TheCall->getNumArgs();
373 
374   if (NumArgs < 4) {
375     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
376     return true;
377   }
378 
379   Expr *Arg0 = TheCall->getArg(0);
380   Expr *Arg1 = TheCall->getArg(1);
381   Expr *Arg2 = TheCall->getArg(2);
382   Expr *Arg3 = TheCall->getArg(3);
383 
384   // First argument always needs to be a queue_t type.
385   if (!Arg0->getType()->isQueueT()) {
386     S.Diag(TheCall->getArg(0)->getLocStart(),
387            diag::err_opencl_enqueue_kernel_expected_type)
388         << S.Context.OCLQueueTy;
389     return true;
390   }
391 
392   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
393   if (!Arg1->getType()->isIntegerType()) {
394     S.Diag(TheCall->getArg(1)->getLocStart(),
395            diag::err_opencl_enqueue_kernel_expected_type)
396         << "'kernel_enqueue_flags_t' (i.e. uint)";
397     return true;
398   }
399 
400   // Third argument is always an ndrange_t type.
401   if (!Arg2->getType()->isNDRangeT()) {
402     S.Diag(TheCall->getArg(2)->getLocStart(),
403            diag::err_opencl_enqueue_kernel_expected_type)
404         << S.Context.OCLNDRangeTy;
405     return true;
406   }
407 
408   // With four arguments, there is only one form that the function could be
409   // called in: no events and no variable arguments.
410   if (NumArgs == 4) {
411     // check that the last argument is the right block type.
412     if (!isBlockPointer(Arg3)) {
413       S.Diag(Arg3->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
414           << "block";
415       return true;
416     }
417     // we have a block type, check the prototype
418     const BlockPointerType *BPT =
419         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
420     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
421       S.Diag(Arg3->getLocStart(),
422              diag::err_opencl_enqueue_kernel_blocks_no_args);
423       return true;
424     }
425     return false;
426   }
427   // we can have block + varargs.
428   if (isBlockPointer(Arg3))
429     return (checkOpenCLBlockArgs(S, Arg3) ||
430             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
431   // last two cases with either exactly 7 args or 7 args and varargs.
432   if (NumArgs >= 7) {
433     // check common block argument.
434     Expr *Arg6 = TheCall->getArg(6);
435     if (!isBlockPointer(Arg6)) {
436       S.Diag(Arg6->getLocStart(), diag::err_opencl_enqueue_kernel_expected_type)
437           << "block";
438       return true;
439     }
440     if (checkOpenCLBlockArgs(S, Arg6))
441       return true;
442 
443     // Forth argument has to be any integer type.
444     if (!Arg3->getType()->isIntegerType()) {
445       S.Diag(TheCall->getArg(3)->getLocStart(),
446              diag::err_opencl_enqueue_kernel_expected_type)
447           << "integer";
448       return true;
449     }
450     // check remaining common arguments.
451     Expr *Arg4 = TheCall->getArg(4);
452     Expr *Arg5 = TheCall->getArg(5);
453 
454     // Fith argument is always passed as pointers to clk_event_t.
455     if (!Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
456       S.Diag(TheCall->getArg(4)->getLocStart(),
457              diag::err_opencl_enqueue_kernel_expected_type)
458           << S.Context.getPointerType(S.Context.OCLClkEventTy);
459       return true;
460     }
461 
462     // Sixth argument is always passed as pointers to clk_event_t.
463     if (!(Arg5->getType()->isPointerType() &&
464           Arg5->getType()->getPointeeType()->isClkEventT())) {
465       S.Diag(TheCall->getArg(5)->getLocStart(),
466              diag::err_opencl_enqueue_kernel_expected_type)
467           << S.Context.getPointerType(S.Context.OCLClkEventTy);
468       return true;
469     }
470 
471     if (NumArgs == 7)
472       return false;
473 
474     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
475   }
476 
477   // None of the specific case has been detected, give generic error
478   S.Diag(TheCall->getLocStart(),
479          diag::err_opencl_enqueue_kernel_incorrect_args);
480   return true;
481 }
482 
483 /// Returns OpenCL access qual.
484 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
485     return D->getAttr<OpenCLAccessAttr>();
486 }
487 
488 /// Returns true if pipe element type is different from the pointer.
489 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
490   const Expr *Arg0 = Call->getArg(0);
491   // First argument type should always be pipe.
492   if (!Arg0->getType()->isPipeType()) {
493     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
494         << Call->getDirectCallee() << Arg0->getSourceRange();
495     return true;
496   }
497   OpenCLAccessAttr *AccessQual =
498       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
499   // Validates the access qualifier is compatible with the call.
500   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
501   // read_only and write_only, and assumed to be read_only if no qualifier is
502   // specified.
503   switch (Call->getDirectCallee()->getBuiltinID()) {
504   case Builtin::BIread_pipe:
505   case Builtin::BIreserve_read_pipe:
506   case Builtin::BIcommit_read_pipe:
507   case Builtin::BIwork_group_reserve_read_pipe:
508   case Builtin::BIsub_group_reserve_read_pipe:
509   case Builtin::BIwork_group_commit_read_pipe:
510   case Builtin::BIsub_group_commit_read_pipe:
511     if (!(!AccessQual || AccessQual->isReadOnly())) {
512       S.Diag(Arg0->getLocStart(),
513              diag::err_opencl_builtin_pipe_invalid_access_modifier)
514           << "read_only" << Arg0->getSourceRange();
515       return true;
516     }
517     break;
518   case Builtin::BIwrite_pipe:
519   case Builtin::BIreserve_write_pipe:
520   case Builtin::BIcommit_write_pipe:
521   case Builtin::BIwork_group_reserve_write_pipe:
522   case Builtin::BIsub_group_reserve_write_pipe:
523   case Builtin::BIwork_group_commit_write_pipe:
524   case Builtin::BIsub_group_commit_write_pipe:
525     if (!(AccessQual && AccessQual->isWriteOnly())) {
526       S.Diag(Arg0->getLocStart(),
527              diag::err_opencl_builtin_pipe_invalid_access_modifier)
528           << "write_only" << Arg0->getSourceRange();
529       return true;
530     }
531     break;
532   default:
533     break;
534   }
535   return false;
536 }
537 
538 /// Returns true if pipe element type is different from the pointer.
539 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
540   const Expr *Arg0 = Call->getArg(0);
541   const Expr *ArgIdx = Call->getArg(Idx);
542   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
543   const QualType EltTy = PipeTy->getElementType();
544   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
545   // The Idx argument should be a pointer and the type of the pointer and
546   // the type of pipe element should also be the same.
547   if (!ArgTy ||
548       !S.Context.hasSameType(
549           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
550     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
551         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
552         << ArgIdx->getType() << ArgIdx->getSourceRange();
553     return true;
554   }
555   return false;
556 }
557 
558 // \brief Performs semantic analysis for the read/write_pipe call.
559 // \param S Reference to the semantic analyzer.
560 // \param Call A pointer to the builtin call.
561 // \return True if a semantic error has been found, false otherwise.
562 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
563   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
564   // functions have two forms.
565   switch (Call->getNumArgs()) {
566   case 2: {
567     if (checkOpenCLPipeArg(S, Call))
568       return true;
569     // The call with 2 arguments should be
570     // read/write_pipe(pipe T, T*).
571     // Check packet type T.
572     if (checkOpenCLPipePacketType(S, Call, 1))
573       return true;
574   } break;
575 
576   case 4: {
577     if (checkOpenCLPipeArg(S, Call))
578       return true;
579     // The call with 4 arguments should be
580     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
581     // Check reserve_id_t.
582     if (!Call->getArg(1)->getType()->isReserveIDT()) {
583       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
584           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
585           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
586       return true;
587     }
588 
589     // Check the index.
590     const Expr *Arg2 = Call->getArg(2);
591     if (!Arg2->getType()->isIntegerType() &&
592         !Arg2->getType()->isUnsignedIntegerType()) {
593       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
594           << Call->getDirectCallee() << S.Context.UnsignedIntTy
595           << Arg2->getType() << Arg2->getSourceRange();
596       return true;
597     }
598 
599     // Check packet type T.
600     if (checkOpenCLPipePacketType(S, Call, 3))
601       return true;
602   } break;
603   default:
604     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
605         << Call->getDirectCallee() << Call->getSourceRange();
606     return true;
607   }
608 
609   return false;
610 }
611 
612 // \brief Performs a semantic analysis on the {work_group_/sub_group_
613 //        /_}reserve_{read/write}_pipe
614 // \param S Reference to the semantic analyzer.
615 // \param Call The call to the builtin function to be analyzed.
616 // \return True if a semantic error was found, false otherwise.
617 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
618   if (checkArgCount(S, Call, 2))
619     return true;
620 
621   if (checkOpenCLPipeArg(S, Call))
622     return true;
623 
624   // Check the reserve size.
625   if (!Call->getArg(1)->getType()->isIntegerType() &&
626       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
627     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
628         << Call->getDirectCallee() << S.Context.UnsignedIntTy
629         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
630     return true;
631   }
632 
633   return false;
634 }
635 
636 // \brief Performs a semantic analysis on {work_group_/sub_group_
637 //        /_}commit_{read/write}_pipe
638 // \param S Reference to the semantic analyzer.
639 // \param Call The call to the builtin function to be analyzed.
640 // \return True if a semantic error was found, false otherwise.
641 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
642   if (checkArgCount(S, Call, 2))
643     return true;
644 
645   if (checkOpenCLPipeArg(S, Call))
646     return true;
647 
648   // Check reserve_id_t.
649   if (!Call->getArg(1)->getType()->isReserveIDT()) {
650     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
651         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
652         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
653     return true;
654   }
655 
656   return false;
657 }
658 
659 // \brief Performs a semantic analysis on the call to built-in Pipe
660 //        Query Functions.
661 // \param S Reference to the semantic analyzer.
662 // \param Call The call to the builtin function to be analyzed.
663 // \return True if a semantic error was found, false otherwise.
664 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
665   if (checkArgCount(S, Call, 1))
666     return true;
667 
668   if (!Call->getArg(0)->getType()->isPipeType()) {
669     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
670         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
671     return true;
672   }
673 
674   return false;
675 }
676 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
677 // \brief Performs semantic analysis for the to_global/local/private call.
678 // \param S Reference to the semantic analyzer.
679 // \param BuiltinID ID of the builtin function.
680 // \param Call A pointer to the builtin call.
681 // \return True if a semantic error has been found, false otherwise.
682 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
683                                     CallExpr *Call) {
684   if (Call->getNumArgs() != 1) {
685     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
686         << Call->getDirectCallee() << Call->getSourceRange();
687     return true;
688   }
689 
690   auto RT = Call->getArg(0)->getType();
691   if (!RT->isPointerType() || RT->getPointeeType()
692       .getAddressSpace() == LangAS::opencl_constant) {
693     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
694         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
695     return true;
696   }
697 
698   RT = RT->getPointeeType();
699   auto Qual = RT.getQualifiers();
700   switch (BuiltinID) {
701   case Builtin::BIto_global:
702     Qual.setAddressSpace(LangAS::opencl_global);
703     break;
704   case Builtin::BIto_local:
705     Qual.setAddressSpace(LangAS::opencl_local);
706     break;
707   default:
708     Qual.removeAddressSpace();
709   }
710   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
711       RT.getUnqualifiedType(), Qual)));
712 
713   return false;
714 }
715 
716 ExprResult
717 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
718                                CallExpr *TheCall) {
719   ExprResult TheCallResult(TheCall);
720 
721   // Find out if any arguments are required to be integer constant expressions.
722   unsigned ICEArguments = 0;
723   ASTContext::GetBuiltinTypeError Error;
724   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
725   if (Error != ASTContext::GE_None)
726     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
727 
728   // If any arguments are required to be ICE's, check and diagnose.
729   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
730     // Skip arguments not required to be ICE's.
731     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
732 
733     llvm::APSInt Result;
734     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
735       return true;
736     ICEArguments &= ~(1 << ArgNo);
737   }
738 
739   switch (BuiltinID) {
740   case Builtin::BI__builtin___CFStringMakeConstantString:
741     assert(TheCall->getNumArgs() == 1 &&
742            "Wrong # arguments to builtin CFStringMakeConstantString");
743     if (CheckObjCString(TheCall->getArg(0)))
744       return ExprError();
745     break;
746   case Builtin::BI__builtin_stdarg_start:
747   case Builtin::BI__builtin_va_start:
748     if (SemaBuiltinVAStart(TheCall))
749       return ExprError();
750     break;
751   case Builtin::BI__va_start: {
752     switch (Context.getTargetInfo().getTriple().getArch()) {
753     case llvm::Triple::arm:
754     case llvm::Triple::thumb:
755       if (SemaBuiltinVAStartARM(TheCall))
756         return ExprError();
757       break;
758     default:
759       if (SemaBuiltinVAStart(TheCall))
760         return ExprError();
761       break;
762     }
763     break;
764   }
765   case Builtin::BI__builtin_isgreater:
766   case Builtin::BI__builtin_isgreaterequal:
767   case Builtin::BI__builtin_isless:
768   case Builtin::BI__builtin_islessequal:
769   case Builtin::BI__builtin_islessgreater:
770   case Builtin::BI__builtin_isunordered:
771     if (SemaBuiltinUnorderedCompare(TheCall))
772       return ExprError();
773     break;
774   case Builtin::BI__builtin_fpclassify:
775     if (SemaBuiltinFPClassification(TheCall, 6))
776       return ExprError();
777     break;
778   case Builtin::BI__builtin_isfinite:
779   case Builtin::BI__builtin_isinf:
780   case Builtin::BI__builtin_isinf_sign:
781   case Builtin::BI__builtin_isnan:
782   case Builtin::BI__builtin_isnormal:
783     if (SemaBuiltinFPClassification(TheCall, 1))
784       return ExprError();
785     break;
786   case Builtin::BI__builtin_shufflevector:
787     return SemaBuiltinShuffleVector(TheCall);
788     // TheCall will be freed by the smart pointer here, but that's fine, since
789     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
790   case Builtin::BI__builtin_prefetch:
791     if (SemaBuiltinPrefetch(TheCall))
792       return ExprError();
793     break;
794   case Builtin::BI__assume:
795   case Builtin::BI__builtin_assume:
796     if (SemaBuiltinAssume(TheCall))
797       return ExprError();
798     break;
799   case Builtin::BI__builtin_assume_aligned:
800     if (SemaBuiltinAssumeAligned(TheCall))
801       return ExprError();
802     break;
803   case Builtin::BI__builtin_object_size:
804     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
805       return ExprError();
806     break;
807   case Builtin::BI__builtin_longjmp:
808     if (SemaBuiltinLongjmp(TheCall))
809       return ExprError();
810     break;
811   case Builtin::BI__builtin_setjmp:
812     if (SemaBuiltinSetjmp(TheCall))
813       return ExprError();
814     break;
815   case Builtin::BI_setjmp:
816   case Builtin::BI_setjmpex:
817     if (checkArgCount(*this, TheCall, 1))
818       return true;
819     break;
820 
821   case Builtin::BI__builtin_classify_type:
822     if (checkArgCount(*this, TheCall, 1)) return true;
823     TheCall->setType(Context.IntTy);
824     break;
825   case Builtin::BI__builtin_constant_p:
826     if (checkArgCount(*this, TheCall, 1)) return true;
827     TheCall->setType(Context.IntTy);
828     break;
829   case Builtin::BI__sync_fetch_and_add:
830   case Builtin::BI__sync_fetch_and_add_1:
831   case Builtin::BI__sync_fetch_and_add_2:
832   case Builtin::BI__sync_fetch_and_add_4:
833   case Builtin::BI__sync_fetch_and_add_8:
834   case Builtin::BI__sync_fetch_and_add_16:
835   case Builtin::BI__sync_fetch_and_sub:
836   case Builtin::BI__sync_fetch_and_sub_1:
837   case Builtin::BI__sync_fetch_and_sub_2:
838   case Builtin::BI__sync_fetch_and_sub_4:
839   case Builtin::BI__sync_fetch_and_sub_8:
840   case Builtin::BI__sync_fetch_and_sub_16:
841   case Builtin::BI__sync_fetch_and_or:
842   case Builtin::BI__sync_fetch_and_or_1:
843   case Builtin::BI__sync_fetch_and_or_2:
844   case Builtin::BI__sync_fetch_and_or_4:
845   case Builtin::BI__sync_fetch_and_or_8:
846   case Builtin::BI__sync_fetch_and_or_16:
847   case Builtin::BI__sync_fetch_and_and:
848   case Builtin::BI__sync_fetch_and_and_1:
849   case Builtin::BI__sync_fetch_and_and_2:
850   case Builtin::BI__sync_fetch_and_and_4:
851   case Builtin::BI__sync_fetch_and_and_8:
852   case Builtin::BI__sync_fetch_and_and_16:
853   case Builtin::BI__sync_fetch_and_xor:
854   case Builtin::BI__sync_fetch_and_xor_1:
855   case Builtin::BI__sync_fetch_and_xor_2:
856   case Builtin::BI__sync_fetch_and_xor_4:
857   case Builtin::BI__sync_fetch_and_xor_8:
858   case Builtin::BI__sync_fetch_and_xor_16:
859   case Builtin::BI__sync_fetch_and_nand:
860   case Builtin::BI__sync_fetch_and_nand_1:
861   case Builtin::BI__sync_fetch_and_nand_2:
862   case Builtin::BI__sync_fetch_and_nand_4:
863   case Builtin::BI__sync_fetch_and_nand_8:
864   case Builtin::BI__sync_fetch_and_nand_16:
865   case Builtin::BI__sync_add_and_fetch:
866   case Builtin::BI__sync_add_and_fetch_1:
867   case Builtin::BI__sync_add_and_fetch_2:
868   case Builtin::BI__sync_add_and_fetch_4:
869   case Builtin::BI__sync_add_and_fetch_8:
870   case Builtin::BI__sync_add_and_fetch_16:
871   case Builtin::BI__sync_sub_and_fetch:
872   case Builtin::BI__sync_sub_and_fetch_1:
873   case Builtin::BI__sync_sub_and_fetch_2:
874   case Builtin::BI__sync_sub_and_fetch_4:
875   case Builtin::BI__sync_sub_and_fetch_8:
876   case Builtin::BI__sync_sub_and_fetch_16:
877   case Builtin::BI__sync_and_and_fetch:
878   case Builtin::BI__sync_and_and_fetch_1:
879   case Builtin::BI__sync_and_and_fetch_2:
880   case Builtin::BI__sync_and_and_fetch_4:
881   case Builtin::BI__sync_and_and_fetch_8:
882   case Builtin::BI__sync_and_and_fetch_16:
883   case Builtin::BI__sync_or_and_fetch:
884   case Builtin::BI__sync_or_and_fetch_1:
885   case Builtin::BI__sync_or_and_fetch_2:
886   case Builtin::BI__sync_or_and_fetch_4:
887   case Builtin::BI__sync_or_and_fetch_8:
888   case Builtin::BI__sync_or_and_fetch_16:
889   case Builtin::BI__sync_xor_and_fetch:
890   case Builtin::BI__sync_xor_and_fetch_1:
891   case Builtin::BI__sync_xor_and_fetch_2:
892   case Builtin::BI__sync_xor_and_fetch_4:
893   case Builtin::BI__sync_xor_and_fetch_8:
894   case Builtin::BI__sync_xor_and_fetch_16:
895   case Builtin::BI__sync_nand_and_fetch:
896   case Builtin::BI__sync_nand_and_fetch_1:
897   case Builtin::BI__sync_nand_and_fetch_2:
898   case Builtin::BI__sync_nand_and_fetch_4:
899   case Builtin::BI__sync_nand_and_fetch_8:
900   case Builtin::BI__sync_nand_and_fetch_16:
901   case Builtin::BI__sync_val_compare_and_swap:
902   case Builtin::BI__sync_val_compare_and_swap_1:
903   case Builtin::BI__sync_val_compare_and_swap_2:
904   case Builtin::BI__sync_val_compare_and_swap_4:
905   case Builtin::BI__sync_val_compare_and_swap_8:
906   case Builtin::BI__sync_val_compare_and_swap_16:
907   case Builtin::BI__sync_bool_compare_and_swap:
908   case Builtin::BI__sync_bool_compare_and_swap_1:
909   case Builtin::BI__sync_bool_compare_and_swap_2:
910   case Builtin::BI__sync_bool_compare_and_swap_4:
911   case Builtin::BI__sync_bool_compare_and_swap_8:
912   case Builtin::BI__sync_bool_compare_and_swap_16:
913   case Builtin::BI__sync_lock_test_and_set:
914   case Builtin::BI__sync_lock_test_and_set_1:
915   case Builtin::BI__sync_lock_test_and_set_2:
916   case Builtin::BI__sync_lock_test_and_set_4:
917   case Builtin::BI__sync_lock_test_and_set_8:
918   case Builtin::BI__sync_lock_test_and_set_16:
919   case Builtin::BI__sync_lock_release:
920   case Builtin::BI__sync_lock_release_1:
921   case Builtin::BI__sync_lock_release_2:
922   case Builtin::BI__sync_lock_release_4:
923   case Builtin::BI__sync_lock_release_8:
924   case Builtin::BI__sync_lock_release_16:
925   case Builtin::BI__sync_swap:
926   case Builtin::BI__sync_swap_1:
927   case Builtin::BI__sync_swap_2:
928   case Builtin::BI__sync_swap_4:
929   case Builtin::BI__sync_swap_8:
930   case Builtin::BI__sync_swap_16:
931     return SemaBuiltinAtomicOverloaded(TheCallResult);
932   case Builtin::BI__builtin_nontemporal_load:
933   case Builtin::BI__builtin_nontemporal_store:
934     return SemaBuiltinNontemporalOverloaded(TheCallResult);
935 #define BUILTIN(ID, TYPE, ATTRS)
936 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
937   case Builtin::BI##ID: \
938     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
939 #include "clang/Basic/Builtins.def"
940   case Builtin::BI__builtin_annotation:
941     if (SemaBuiltinAnnotation(*this, TheCall))
942       return ExprError();
943     break;
944   case Builtin::BI__builtin_addressof:
945     if (SemaBuiltinAddressof(*this, TheCall))
946       return ExprError();
947     break;
948   case Builtin::BI__builtin_add_overflow:
949   case Builtin::BI__builtin_sub_overflow:
950   case Builtin::BI__builtin_mul_overflow:
951     if (SemaBuiltinOverflow(*this, TheCall))
952       return ExprError();
953     break;
954   case Builtin::BI__builtin_operator_new:
955   case Builtin::BI__builtin_operator_delete:
956     if (!getLangOpts().CPlusPlus) {
957       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
958         << (BuiltinID == Builtin::BI__builtin_operator_new
959                 ? "__builtin_operator_new"
960                 : "__builtin_operator_delete")
961         << "C++";
962       return ExprError();
963     }
964     // CodeGen assumes it can find the global new and delete to call,
965     // so ensure that they are declared.
966     DeclareGlobalNewDelete();
967     break;
968 
969   // check secure string manipulation functions where overflows
970   // are detectable at compile time
971   case Builtin::BI__builtin___memcpy_chk:
972   case Builtin::BI__builtin___memmove_chk:
973   case Builtin::BI__builtin___memset_chk:
974   case Builtin::BI__builtin___strlcat_chk:
975   case Builtin::BI__builtin___strlcpy_chk:
976   case Builtin::BI__builtin___strncat_chk:
977   case Builtin::BI__builtin___strncpy_chk:
978   case Builtin::BI__builtin___stpncpy_chk:
979     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
980     break;
981   case Builtin::BI__builtin___memccpy_chk:
982     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
983     break;
984   case Builtin::BI__builtin___snprintf_chk:
985   case Builtin::BI__builtin___vsnprintf_chk:
986     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
987     break;
988   case Builtin::BI__builtin_call_with_static_chain:
989     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
990       return ExprError();
991     break;
992   case Builtin::BI__exception_code:
993   case Builtin::BI_exception_code:
994     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
995                                  diag::err_seh___except_block))
996       return ExprError();
997     break;
998   case Builtin::BI__exception_info:
999   case Builtin::BI_exception_info:
1000     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1001                                  diag::err_seh___except_filter))
1002       return ExprError();
1003     break;
1004   case Builtin::BI__GetExceptionInfo:
1005     if (checkArgCount(*this, TheCall, 1))
1006       return ExprError();
1007 
1008     if (CheckCXXThrowOperand(
1009             TheCall->getLocStart(),
1010             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1011             TheCall))
1012       return ExprError();
1013 
1014     TheCall->setType(Context.VoidPtrTy);
1015     break;
1016   // OpenCL v2.0, s6.13.16 - Pipe functions
1017   case Builtin::BIread_pipe:
1018   case Builtin::BIwrite_pipe:
1019     // Since those two functions are declared with var args, we need a semantic
1020     // check for the argument.
1021     if (SemaBuiltinRWPipe(*this, TheCall))
1022       return ExprError();
1023     TheCall->setType(Context.IntTy);
1024     break;
1025   case Builtin::BIreserve_read_pipe:
1026   case Builtin::BIreserve_write_pipe:
1027   case Builtin::BIwork_group_reserve_read_pipe:
1028   case Builtin::BIwork_group_reserve_write_pipe:
1029   case Builtin::BIsub_group_reserve_read_pipe:
1030   case Builtin::BIsub_group_reserve_write_pipe:
1031     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1032       return ExprError();
1033     // Since return type of reserve_read/write_pipe built-in function is
1034     // reserve_id_t, which is not defined in the builtin def file , we used int
1035     // as return type and need to override the return type of these functions.
1036     TheCall->setType(Context.OCLReserveIDTy);
1037     break;
1038   case Builtin::BIcommit_read_pipe:
1039   case Builtin::BIcommit_write_pipe:
1040   case Builtin::BIwork_group_commit_read_pipe:
1041   case Builtin::BIwork_group_commit_write_pipe:
1042   case Builtin::BIsub_group_commit_read_pipe:
1043   case Builtin::BIsub_group_commit_write_pipe:
1044     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1045       return ExprError();
1046     break;
1047   case Builtin::BIget_pipe_num_packets:
1048   case Builtin::BIget_pipe_max_packets:
1049     if (SemaBuiltinPipePackets(*this, TheCall))
1050       return ExprError();
1051     TheCall->setType(Context.UnsignedIntTy);
1052     break;
1053   case Builtin::BIto_global:
1054   case Builtin::BIto_local:
1055   case Builtin::BIto_private:
1056     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1057       return ExprError();
1058     break;
1059   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1060   case Builtin::BIenqueue_kernel:
1061     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1062       return ExprError();
1063     break;
1064   case Builtin::BIget_kernel_work_group_size:
1065   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1066     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1067       return ExprError();
1068   }
1069 
1070   // Since the target specific builtins for each arch overlap, only check those
1071   // of the arch we are compiling for.
1072   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1073     switch (Context.getTargetInfo().getTriple().getArch()) {
1074       case llvm::Triple::arm:
1075       case llvm::Triple::armeb:
1076       case llvm::Triple::thumb:
1077       case llvm::Triple::thumbeb:
1078         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1079           return ExprError();
1080         break;
1081       case llvm::Triple::aarch64:
1082       case llvm::Triple::aarch64_be:
1083         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1084           return ExprError();
1085         break;
1086       case llvm::Triple::mips:
1087       case llvm::Triple::mipsel:
1088       case llvm::Triple::mips64:
1089       case llvm::Triple::mips64el:
1090         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1091           return ExprError();
1092         break;
1093       case llvm::Triple::systemz:
1094         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1095           return ExprError();
1096         break;
1097       case llvm::Triple::x86:
1098       case llvm::Triple::x86_64:
1099         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1100           return ExprError();
1101         break;
1102       case llvm::Triple::ppc:
1103       case llvm::Triple::ppc64:
1104       case llvm::Triple::ppc64le:
1105         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1106           return ExprError();
1107         break;
1108       default:
1109         break;
1110     }
1111   }
1112 
1113   return TheCallResult;
1114 }
1115 
1116 // Get the valid immediate range for the specified NEON type code.
1117 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1118   NeonTypeFlags Type(t);
1119   int IsQuad = ForceQuad ? true : Type.isQuad();
1120   switch (Type.getEltType()) {
1121   case NeonTypeFlags::Int8:
1122   case NeonTypeFlags::Poly8:
1123     return shift ? 7 : (8 << IsQuad) - 1;
1124   case NeonTypeFlags::Int16:
1125   case NeonTypeFlags::Poly16:
1126     return shift ? 15 : (4 << IsQuad) - 1;
1127   case NeonTypeFlags::Int32:
1128     return shift ? 31 : (2 << IsQuad) - 1;
1129   case NeonTypeFlags::Int64:
1130   case NeonTypeFlags::Poly64:
1131     return shift ? 63 : (1 << IsQuad) - 1;
1132   case NeonTypeFlags::Poly128:
1133     return shift ? 127 : (1 << IsQuad) - 1;
1134   case NeonTypeFlags::Float16:
1135     assert(!shift && "cannot shift float types!");
1136     return (4 << IsQuad) - 1;
1137   case NeonTypeFlags::Float32:
1138     assert(!shift && "cannot shift float types!");
1139     return (2 << IsQuad) - 1;
1140   case NeonTypeFlags::Float64:
1141     assert(!shift && "cannot shift float types!");
1142     return (1 << IsQuad) - 1;
1143   }
1144   llvm_unreachable("Invalid NeonTypeFlag!");
1145 }
1146 
1147 /// getNeonEltType - Return the QualType corresponding to the elements of
1148 /// the vector type specified by the NeonTypeFlags.  This is used to check
1149 /// the pointer arguments for Neon load/store intrinsics.
1150 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1151                                bool IsPolyUnsigned, bool IsInt64Long) {
1152   switch (Flags.getEltType()) {
1153   case NeonTypeFlags::Int8:
1154     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1155   case NeonTypeFlags::Int16:
1156     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1157   case NeonTypeFlags::Int32:
1158     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1159   case NeonTypeFlags::Int64:
1160     if (IsInt64Long)
1161       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1162     else
1163       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1164                                 : Context.LongLongTy;
1165   case NeonTypeFlags::Poly8:
1166     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1167   case NeonTypeFlags::Poly16:
1168     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1169   case NeonTypeFlags::Poly64:
1170     if (IsInt64Long)
1171       return Context.UnsignedLongTy;
1172     else
1173       return Context.UnsignedLongLongTy;
1174   case NeonTypeFlags::Poly128:
1175     break;
1176   case NeonTypeFlags::Float16:
1177     return Context.HalfTy;
1178   case NeonTypeFlags::Float32:
1179     return Context.FloatTy;
1180   case NeonTypeFlags::Float64:
1181     return Context.DoubleTy;
1182   }
1183   llvm_unreachable("Invalid NeonTypeFlag!");
1184 }
1185 
1186 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1187   llvm::APSInt Result;
1188   uint64_t mask = 0;
1189   unsigned TV = 0;
1190   int PtrArgNum = -1;
1191   bool HasConstPtr = false;
1192   switch (BuiltinID) {
1193 #define GET_NEON_OVERLOAD_CHECK
1194 #include "clang/Basic/arm_neon.inc"
1195 #undef GET_NEON_OVERLOAD_CHECK
1196   }
1197 
1198   // For NEON intrinsics which are overloaded on vector element type, validate
1199   // the immediate which specifies which variant to emit.
1200   unsigned ImmArg = TheCall->getNumArgs()-1;
1201   if (mask) {
1202     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1203       return true;
1204 
1205     TV = Result.getLimitedValue(64);
1206     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1207       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1208         << TheCall->getArg(ImmArg)->getSourceRange();
1209   }
1210 
1211   if (PtrArgNum >= 0) {
1212     // Check that pointer arguments have the specified type.
1213     Expr *Arg = TheCall->getArg(PtrArgNum);
1214     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1215       Arg = ICE->getSubExpr();
1216     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1217     QualType RHSTy = RHS.get()->getType();
1218 
1219     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1220     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
1221     bool IsInt64Long =
1222         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1223     QualType EltTy =
1224         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1225     if (HasConstPtr)
1226       EltTy = EltTy.withConst();
1227     QualType LHSTy = Context.getPointerType(EltTy);
1228     AssignConvertType ConvTy;
1229     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1230     if (RHS.isInvalid())
1231       return true;
1232     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1233                                  RHS.get(), AA_Assigning))
1234       return true;
1235   }
1236 
1237   // For NEON intrinsics which take an immediate value as part of the
1238   // instruction, range check them here.
1239   unsigned i = 0, l = 0, u = 0;
1240   switch (BuiltinID) {
1241   default:
1242     return false;
1243 #define GET_NEON_IMMEDIATE_CHECK
1244 #include "clang/Basic/arm_neon.inc"
1245 #undef GET_NEON_IMMEDIATE_CHECK
1246   }
1247 
1248   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1249 }
1250 
1251 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1252                                         unsigned MaxWidth) {
1253   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1254           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1255           BuiltinID == ARM::BI__builtin_arm_strex ||
1256           BuiltinID == ARM::BI__builtin_arm_stlex ||
1257           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1258           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1259           BuiltinID == AArch64::BI__builtin_arm_strex ||
1260           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1261          "unexpected ARM builtin");
1262   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1263                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1264                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1265                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1266 
1267   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1268 
1269   // Ensure that we have the proper number of arguments.
1270   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1271     return true;
1272 
1273   // Inspect the pointer argument of the atomic builtin.  This should always be
1274   // a pointer type, whose element is an integral scalar or pointer type.
1275   // Because it is a pointer type, we don't have to worry about any implicit
1276   // casts here.
1277   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1278   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1279   if (PointerArgRes.isInvalid())
1280     return true;
1281   PointerArg = PointerArgRes.get();
1282 
1283   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1284   if (!pointerType) {
1285     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1286       << PointerArg->getType() << PointerArg->getSourceRange();
1287     return true;
1288   }
1289 
1290   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1291   // task is to insert the appropriate casts into the AST. First work out just
1292   // what the appropriate type is.
1293   QualType ValType = pointerType->getPointeeType();
1294   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1295   if (IsLdrex)
1296     AddrType.addConst();
1297 
1298   // Issue a warning if the cast is dodgy.
1299   CastKind CastNeeded = CK_NoOp;
1300   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1301     CastNeeded = CK_BitCast;
1302     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1303       << PointerArg->getType()
1304       << Context.getPointerType(AddrType)
1305       << AA_Passing << PointerArg->getSourceRange();
1306   }
1307 
1308   // Finally, do the cast and replace the argument with the corrected version.
1309   AddrType = Context.getPointerType(AddrType);
1310   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1311   if (PointerArgRes.isInvalid())
1312     return true;
1313   PointerArg = PointerArgRes.get();
1314 
1315   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1316 
1317   // In general, we allow ints, floats and pointers to be loaded and stored.
1318   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1319       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1320     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1321       << PointerArg->getType() << PointerArg->getSourceRange();
1322     return true;
1323   }
1324 
1325   // But ARM doesn't have instructions to deal with 128-bit versions.
1326   if (Context.getTypeSize(ValType) > MaxWidth) {
1327     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1328     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1329       << PointerArg->getType() << PointerArg->getSourceRange();
1330     return true;
1331   }
1332 
1333   switch (ValType.getObjCLifetime()) {
1334   case Qualifiers::OCL_None:
1335   case Qualifiers::OCL_ExplicitNone:
1336     // okay
1337     break;
1338 
1339   case Qualifiers::OCL_Weak:
1340   case Qualifiers::OCL_Strong:
1341   case Qualifiers::OCL_Autoreleasing:
1342     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1343       << ValType << PointerArg->getSourceRange();
1344     return true;
1345   }
1346 
1347   if (IsLdrex) {
1348     TheCall->setType(ValType);
1349     return false;
1350   }
1351 
1352   // Initialize the argument to be stored.
1353   ExprResult ValArg = TheCall->getArg(0);
1354   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1355       Context, ValType, /*consume*/ false);
1356   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1357   if (ValArg.isInvalid())
1358     return true;
1359   TheCall->setArg(0, ValArg.get());
1360 
1361   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1362   // but the custom checker bypasses all default analysis.
1363   TheCall->setType(Context.IntTy);
1364   return false;
1365 }
1366 
1367 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1368   llvm::APSInt Result;
1369 
1370   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1371       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1372       BuiltinID == ARM::BI__builtin_arm_strex ||
1373       BuiltinID == ARM::BI__builtin_arm_stlex) {
1374     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1375   }
1376 
1377   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1378     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1379       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1380   }
1381 
1382   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1383       BuiltinID == ARM::BI__builtin_arm_wsr64)
1384     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1385 
1386   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1387       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1388       BuiltinID == ARM::BI__builtin_arm_wsr ||
1389       BuiltinID == ARM::BI__builtin_arm_wsrp)
1390     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1391 
1392   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1393     return true;
1394 
1395   // For intrinsics which take an immediate value as part of the instruction,
1396   // range check them here.
1397   unsigned i = 0, l = 0, u = 0;
1398   switch (BuiltinID) {
1399   default: return false;
1400   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1401   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1402   case ARM::BI__builtin_arm_vcvtr_f:
1403   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1404   case ARM::BI__builtin_arm_dmb:
1405   case ARM::BI__builtin_arm_dsb:
1406   case ARM::BI__builtin_arm_isb:
1407   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1408   }
1409 
1410   // FIXME: VFP Intrinsics should error if VFP not present.
1411   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1412 }
1413 
1414 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1415                                          CallExpr *TheCall) {
1416   llvm::APSInt Result;
1417 
1418   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1419       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1420       BuiltinID == AArch64::BI__builtin_arm_strex ||
1421       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1422     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1423   }
1424 
1425   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1426     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1427       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1428       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1429       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1430   }
1431 
1432   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1433       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1434     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1435 
1436   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1437       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1438       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1439       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1440     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1441 
1442   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1443     return true;
1444 
1445   // For intrinsics which take an immediate value as part of the instruction,
1446   // range check them here.
1447   unsigned i = 0, l = 0, u = 0;
1448   switch (BuiltinID) {
1449   default: return false;
1450   case AArch64::BI__builtin_arm_dmb:
1451   case AArch64::BI__builtin_arm_dsb:
1452   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1453   }
1454 
1455   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1456 }
1457 
1458 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1459   unsigned i = 0, l = 0, u = 0;
1460   switch (BuiltinID) {
1461   default: return false;
1462   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1463   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1464   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1465   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1466   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1467   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1468   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1469   }
1470 
1471   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1472 }
1473 
1474 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475   unsigned i = 0, l = 0, u = 0;
1476   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1477                       BuiltinID == PPC::BI__builtin_divdeu ||
1478                       BuiltinID == PPC::BI__builtin_bpermd;
1479   bool IsTarget64Bit = Context.getTargetInfo()
1480                               .getTypeWidth(Context
1481                                             .getTargetInfo()
1482                                             .getIntPtrType()) == 64;
1483   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1484                        BuiltinID == PPC::BI__builtin_divweu ||
1485                        BuiltinID == PPC::BI__builtin_divde ||
1486                        BuiltinID == PPC::BI__builtin_divdeu;
1487 
1488   if (Is64BitBltin && !IsTarget64Bit)
1489       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1490              << TheCall->getSourceRange();
1491 
1492   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1493       (BuiltinID == PPC::BI__builtin_bpermd &&
1494        !Context.getTargetInfo().hasFeature("bpermd")))
1495     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1496            << TheCall->getSourceRange();
1497 
1498   switch (BuiltinID) {
1499   default: return false;
1500   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1501   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1503            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1504   case PPC::BI__builtin_tbegin:
1505   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1506   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1507   case PPC::BI__builtin_tabortwc:
1508   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1509   case PPC::BI__builtin_tabortwci:
1510   case PPC::BI__builtin_tabortdci:
1511     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1512            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1513   }
1514   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1515 }
1516 
1517 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1518                                            CallExpr *TheCall) {
1519   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1520     Expr *Arg = TheCall->getArg(0);
1521     llvm::APSInt AbortCode(32);
1522     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1523         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1524       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1525              << Arg->getSourceRange();
1526   }
1527 
1528   // For intrinsics which take an immediate value as part of the instruction,
1529   // range check them here.
1530   unsigned i = 0, l = 0, u = 0;
1531   switch (BuiltinID) {
1532   default: return false;
1533   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1534   case SystemZ::BI__builtin_s390_verimb:
1535   case SystemZ::BI__builtin_s390_verimh:
1536   case SystemZ::BI__builtin_s390_verimf:
1537   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1538   case SystemZ::BI__builtin_s390_vfaeb:
1539   case SystemZ::BI__builtin_s390_vfaeh:
1540   case SystemZ::BI__builtin_s390_vfaef:
1541   case SystemZ::BI__builtin_s390_vfaebs:
1542   case SystemZ::BI__builtin_s390_vfaehs:
1543   case SystemZ::BI__builtin_s390_vfaefs:
1544   case SystemZ::BI__builtin_s390_vfaezb:
1545   case SystemZ::BI__builtin_s390_vfaezh:
1546   case SystemZ::BI__builtin_s390_vfaezf:
1547   case SystemZ::BI__builtin_s390_vfaezbs:
1548   case SystemZ::BI__builtin_s390_vfaezhs:
1549   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1550   case SystemZ::BI__builtin_s390_vfidb:
1551     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1552            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1553   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1554   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1555   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1556   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1557   case SystemZ::BI__builtin_s390_vstrcb:
1558   case SystemZ::BI__builtin_s390_vstrch:
1559   case SystemZ::BI__builtin_s390_vstrcf:
1560   case SystemZ::BI__builtin_s390_vstrczb:
1561   case SystemZ::BI__builtin_s390_vstrczh:
1562   case SystemZ::BI__builtin_s390_vstrczf:
1563   case SystemZ::BI__builtin_s390_vstrcbs:
1564   case SystemZ::BI__builtin_s390_vstrchs:
1565   case SystemZ::BI__builtin_s390_vstrcfs:
1566   case SystemZ::BI__builtin_s390_vstrczbs:
1567   case SystemZ::BI__builtin_s390_vstrczhs:
1568   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1569   }
1570   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1571 }
1572 
1573 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1574 /// This checks that the target supports __builtin_cpu_supports and
1575 /// that the string argument is constant and valid.
1576 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1577   Expr *Arg = TheCall->getArg(0);
1578 
1579   // Check if the argument is a string literal.
1580   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1581     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1582            << Arg->getSourceRange();
1583 
1584   // Check the contents of the string.
1585   StringRef Feature =
1586       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1587   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1588     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1589            << Arg->getSourceRange();
1590   return false;
1591 }
1592 
1593 // Check if the rounding mode is legal.
1594 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1595   // Indicates if this instruction has rounding control or just SAE.
1596   bool HasRC = false;
1597 
1598   unsigned ArgNum = 0;
1599   switch (BuiltinID) {
1600   default:
1601     return false;
1602   case X86::BI__builtin_ia32_vcvttsd2si32:
1603   case X86::BI__builtin_ia32_vcvttsd2si64:
1604   case X86::BI__builtin_ia32_vcvttsd2usi32:
1605   case X86::BI__builtin_ia32_vcvttsd2usi64:
1606   case X86::BI__builtin_ia32_vcvttss2si32:
1607   case X86::BI__builtin_ia32_vcvttss2si64:
1608   case X86::BI__builtin_ia32_vcvttss2usi32:
1609   case X86::BI__builtin_ia32_vcvttss2usi64:
1610     ArgNum = 1;
1611     break;
1612   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1613   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1614   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1615   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1616   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1617   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1618   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1619   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1620   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1621   case X86::BI__builtin_ia32_exp2pd_mask:
1622   case X86::BI__builtin_ia32_exp2ps_mask:
1623   case X86::BI__builtin_ia32_getexppd512_mask:
1624   case X86::BI__builtin_ia32_getexpps512_mask:
1625   case X86::BI__builtin_ia32_rcp28pd_mask:
1626   case X86::BI__builtin_ia32_rcp28ps_mask:
1627   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1628   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1629   case X86::BI__builtin_ia32_vcomisd:
1630   case X86::BI__builtin_ia32_vcomiss:
1631   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1632     ArgNum = 3;
1633     break;
1634   case X86::BI__builtin_ia32_cmppd512_mask:
1635   case X86::BI__builtin_ia32_cmpps512_mask:
1636   case X86::BI__builtin_ia32_cmpsd_mask:
1637   case X86::BI__builtin_ia32_cmpss_mask:
1638   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1639   case X86::BI__builtin_ia32_getexpss128_round_mask:
1640   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1641   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1642   case X86::BI__builtin_ia32_reducepd512_mask:
1643   case X86::BI__builtin_ia32_reduceps512_mask:
1644   case X86::BI__builtin_ia32_rndscalepd_mask:
1645   case X86::BI__builtin_ia32_rndscaleps_mask:
1646   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1647   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1648     ArgNum = 4;
1649     break;
1650   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1651   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1652   case X86::BI__builtin_ia32_fixupimmps512_mask:
1653   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1654   case X86::BI__builtin_ia32_fixupimmsd_mask:
1655   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1656   case X86::BI__builtin_ia32_fixupimmss_mask:
1657   case X86::BI__builtin_ia32_fixupimmss_maskz:
1658   case X86::BI__builtin_ia32_rangepd512_mask:
1659   case X86::BI__builtin_ia32_rangeps512_mask:
1660   case X86::BI__builtin_ia32_rangesd128_round_mask:
1661   case X86::BI__builtin_ia32_rangess128_round_mask:
1662   case X86::BI__builtin_ia32_reducesd_mask:
1663   case X86::BI__builtin_ia32_reducess_mask:
1664   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1665   case X86::BI__builtin_ia32_rndscaless_round_mask:
1666     ArgNum = 5;
1667     break;
1668   case X86::BI__builtin_ia32_vcvtsd2si64:
1669   case X86::BI__builtin_ia32_vcvtsd2si32:
1670   case X86::BI__builtin_ia32_vcvtsd2usi32:
1671   case X86::BI__builtin_ia32_vcvtsd2usi64:
1672   case X86::BI__builtin_ia32_vcvtss2si32:
1673   case X86::BI__builtin_ia32_vcvtss2si64:
1674   case X86::BI__builtin_ia32_vcvtss2usi32:
1675   case X86::BI__builtin_ia32_vcvtss2usi64:
1676     ArgNum = 1;
1677     HasRC = true;
1678     break;
1679   case X86::BI__builtin_ia32_cvtusi2sd64:
1680   case X86::BI__builtin_ia32_cvtusi2ss32:
1681   case X86::BI__builtin_ia32_cvtusi2ss64:
1682     ArgNum = 2;
1683     HasRC = true;
1684     break;
1685   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1686   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1687   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1688   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1689   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1690   case X86::BI__builtin_ia32_cvtps2qq512_mask:
1691   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1692   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1693   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1694   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1695   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1696     ArgNum = 3;
1697     HasRC = true;
1698     break;
1699   case X86::BI__builtin_ia32_addpd512_mask:
1700   case X86::BI__builtin_ia32_addps512_mask:
1701   case X86::BI__builtin_ia32_divpd512_mask:
1702   case X86::BI__builtin_ia32_divps512_mask:
1703   case X86::BI__builtin_ia32_mulpd512_mask:
1704   case X86::BI__builtin_ia32_mulps512_mask:
1705   case X86::BI__builtin_ia32_subpd512_mask:
1706   case X86::BI__builtin_ia32_subps512_mask:
1707   case X86::BI__builtin_ia32_addss_round_mask:
1708   case X86::BI__builtin_ia32_addsd_round_mask:
1709   case X86::BI__builtin_ia32_divss_round_mask:
1710   case X86::BI__builtin_ia32_divsd_round_mask:
1711   case X86::BI__builtin_ia32_mulss_round_mask:
1712   case X86::BI__builtin_ia32_mulsd_round_mask:
1713   case X86::BI__builtin_ia32_subss_round_mask:
1714   case X86::BI__builtin_ia32_subsd_round_mask:
1715   case X86::BI__builtin_ia32_scalefpd512_mask:
1716   case X86::BI__builtin_ia32_scalefps512_mask:
1717   case X86::BI__builtin_ia32_scalefsd_round_mask:
1718   case X86::BI__builtin_ia32_scalefss_round_mask:
1719   case X86::BI__builtin_ia32_getmantpd512_mask:
1720   case X86::BI__builtin_ia32_getmantps512_mask:
1721   case X86::BI__builtin_ia32_vfmaddpd512_mask:
1722   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1723   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1724   case X86::BI__builtin_ia32_vfmaddps512_mask:
1725   case X86::BI__builtin_ia32_vfmaddps512_mask3:
1726   case X86::BI__builtin_ia32_vfmaddps512_maskz:
1727   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1728   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1729   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1730   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1731   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1732   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1733   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1734   case X86::BI__builtin_ia32_vfmsubps512_mask3:
1735   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1736   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1737   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1738   case X86::BI__builtin_ia32_vfnmaddps512_mask:
1739   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1740   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1741   case X86::BI__builtin_ia32_vfnmsubps512_mask:
1742   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1743   case X86::BI__builtin_ia32_vfmaddsd3_mask:
1744   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1745   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1746   case X86::BI__builtin_ia32_vfmaddss3_mask:
1747   case X86::BI__builtin_ia32_vfmaddss3_maskz:
1748   case X86::BI__builtin_ia32_vfmaddss3_mask3:
1749     ArgNum = 4;
1750     HasRC = true;
1751     break;
1752   case X86::BI__builtin_ia32_getmantsd_round_mask:
1753   case X86::BI__builtin_ia32_getmantss_round_mask:
1754     ArgNum = 5;
1755     HasRC = true;
1756     break;
1757   }
1758 
1759   llvm::APSInt Result;
1760 
1761   // We can't check the value of a dependent argument.
1762   Expr *Arg = TheCall->getArg(ArgNum);
1763   if (Arg->isTypeDependent() || Arg->isValueDependent())
1764     return false;
1765 
1766   // Check constant-ness first.
1767   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1768     return true;
1769 
1770   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
1771   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
1772   // combined with ROUND_NO_EXC.
1773   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
1774       Result == 8/*ROUND_NO_EXC*/ ||
1775       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1776     return false;
1777 
1778   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
1779     << Arg->getSourceRange();
1780 }
1781 
1782 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1783   if (BuiltinID == X86::BI__builtin_cpu_supports)
1784     return SemaBuiltinCpuSupports(*this, TheCall);
1785 
1786   if (BuiltinID == X86::BI__builtin_ms_va_start)
1787     return SemaBuiltinMSVAStart(TheCall);
1788 
1789   // If the intrinsic has rounding or SAE make sure its valid.
1790   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
1791     return true;
1792 
1793   // For intrinsics which take an immediate value as part of the instruction,
1794   // range check them here.
1795   int i = 0, l = 0, u = 0;
1796   switch (BuiltinID) {
1797   default:
1798     return false;
1799   case X86::BI__builtin_ia32_extractf64x4_mask:
1800   case X86::BI__builtin_ia32_extracti64x4_mask:
1801   case X86::BI__builtin_ia32_extractf32x8_mask:
1802   case X86::BI__builtin_ia32_extracti32x8_mask:
1803   case X86::BI__builtin_ia32_extractf64x2_256_mask:
1804   case X86::BI__builtin_ia32_extracti64x2_256_mask:
1805   case X86::BI__builtin_ia32_extractf32x4_256_mask:
1806   case X86::BI__builtin_ia32_extracti32x4_256_mask:
1807     i = 1; l = 0; u = 1;
1808     break;
1809   case X86::BI_mm_prefetch:
1810   case X86::BI__builtin_ia32_extractf32x4_mask:
1811   case X86::BI__builtin_ia32_extracti32x4_mask:
1812   case X86::BI__builtin_ia32_extractf64x2_512_mask:
1813   case X86::BI__builtin_ia32_extracti64x2_512_mask:
1814     i = 1; l = 0; u = 3;
1815     break;
1816   case X86::BI__builtin_ia32_insertf32x8_mask:
1817   case X86::BI__builtin_ia32_inserti32x8_mask:
1818   case X86::BI__builtin_ia32_insertf64x4_mask:
1819   case X86::BI__builtin_ia32_inserti64x4_mask:
1820   case X86::BI__builtin_ia32_insertf64x2_256_mask:
1821   case X86::BI__builtin_ia32_inserti64x2_256_mask:
1822   case X86::BI__builtin_ia32_insertf32x4_256_mask:
1823   case X86::BI__builtin_ia32_inserti32x4_256_mask:
1824     i = 2; l = 0; u = 1;
1825     break;
1826   case X86::BI__builtin_ia32_sha1rnds4:
1827   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
1828   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
1829   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
1830   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
1831   case X86::BI__builtin_ia32_insertf64x2_512_mask:
1832   case X86::BI__builtin_ia32_inserti64x2_512_mask:
1833   case X86::BI__builtin_ia32_insertf32x4_mask:
1834   case X86::BI__builtin_ia32_inserti32x4_mask:
1835     i = 2; l = 0; u = 3;
1836     break;
1837   case X86::BI__builtin_ia32_vpermil2pd:
1838   case X86::BI__builtin_ia32_vpermil2pd256:
1839   case X86::BI__builtin_ia32_vpermil2ps:
1840   case X86::BI__builtin_ia32_vpermil2ps256:
1841     i = 3; l = 0; u = 3;
1842     break;
1843   case X86::BI__builtin_ia32_cmpb128_mask:
1844   case X86::BI__builtin_ia32_cmpw128_mask:
1845   case X86::BI__builtin_ia32_cmpd128_mask:
1846   case X86::BI__builtin_ia32_cmpq128_mask:
1847   case X86::BI__builtin_ia32_cmpb256_mask:
1848   case X86::BI__builtin_ia32_cmpw256_mask:
1849   case X86::BI__builtin_ia32_cmpd256_mask:
1850   case X86::BI__builtin_ia32_cmpq256_mask:
1851   case X86::BI__builtin_ia32_cmpb512_mask:
1852   case X86::BI__builtin_ia32_cmpw512_mask:
1853   case X86::BI__builtin_ia32_cmpd512_mask:
1854   case X86::BI__builtin_ia32_cmpq512_mask:
1855   case X86::BI__builtin_ia32_ucmpb128_mask:
1856   case X86::BI__builtin_ia32_ucmpw128_mask:
1857   case X86::BI__builtin_ia32_ucmpd128_mask:
1858   case X86::BI__builtin_ia32_ucmpq128_mask:
1859   case X86::BI__builtin_ia32_ucmpb256_mask:
1860   case X86::BI__builtin_ia32_ucmpw256_mask:
1861   case X86::BI__builtin_ia32_ucmpd256_mask:
1862   case X86::BI__builtin_ia32_ucmpq256_mask:
1863   case X86::BI__builtin_ia32_ucmpb512_mask:
1864   case X86::BI__builtin_ia32_ucmpw512_mask:
1865   case X86::BI__builtin_ia32_ucmpd512_mask:
1866   case X86::BI__builtin_ia32_ucmpq512_mask:
1867   case X86::BI__builtin_ia32_vpcomub:
1868   case X86::BI__builtin_ia32_vpcomuw:
1869   case X86::BI__builtin_ia32_vpcomud:
1870   case X86::BI__builtin_ia32_vpcomuq:
1871   case X86::BI__builtin_ia32_vpcomb:
1872   case X86::BI__builtin_ia32_vpcomw:
1873   case X86::BI__builtin_ia32_vpcomd:
1874   case X86::BI__builtin_ia32_vpcomq:
1875     i = 2; l = 0; u = 7;
1876     break;
1877   case X86::BI__builtin_ia32_roundps:
1878   case X86::BI__builtin_ia32_roundpd:
1879   case X86::BI__builtin_ia32_roundps256:
1880   case X86::BI__builtin_ia32_roundpd256:
1881     i = 1; l = 0; u = 15;
1882     break;
1883   case X86::BI__builtin_ia32_roundss:
1884   case X86::BI__builtin_ia32_roundsd:
1885   case X86::BI__builtin_ia32_rangepd128_mask:
1886   case X86::BI__builtin_ia32_rangepd256_mask:
1887   case X86::BI__builtin_ia32_rangepd512_mask:
1888   case X86::BI__builtin_ia32_rangeps128_mask:
1889   case X86::BI__builtin_ia32_rangeps256_mask:
1890   case X86::BI__builtin_ia32_rangeps512_mask:
1891   case X86::BI__builtin_ia32_getmantsd_round_mask:
1892   case X86::BI__builtin_ia32_getmantss_round_mask:
1893     i = 2; l = 0; u = 15;
1894     break;
1895   case X86::BI__builtin_ia32_cmpps:
1896   case X86::BI__builtin_ia32_cmpss:
1897   case X86::BI__builtin_ia32_cmppd:
1898   case X86::BI__builtin_ia32_cmpsd:
1899   case X86::BI__builtin_ia32_cmpps256:
1900   case X86::BI__builtin_ia32_cmppd256:
1901   case X86::BI__builtin_ia32_cmpps128_mask:
1902   case X86::BI__builtin_ia32_cmppd128_mask:
1903   case X86::BI__builtin_ia32_cmpps256_mask:
1904   case X86::BI__builtin_ia32_cmppd256_mask:
1905   case X86::BI__builtin_ia32_cmpps512_mask:
1906   case X86::BI__builtin_ia32_cmppd512_mask:
1907   case X86::BI__builtin_ia32_cmpsd_mask:
1908   case X86::BI__builtin_ia32_cmpss_mask:
1909     i = 2; l = 0; u = 31;
1910     break;
1911   case X86::BI__builtin_ia32_xabort:
1912     i = 0; l = -128; u = 255;
1913     break;
1914   case X86::BI__builtin_ia32_pshufw:
1915   case X86::BI__builtin_ia32_aeskeygenassist128:
1916     i = 1; l = -128; u = 255;
1917     break;
1918   case X86::BI__builtin_ia32_vcvtps2ph:
1919   case X86::BI__builtin_ia32_vcvtps2ph256:
1920   case X86::BI__builtin_ia32_rndscaleps_128_mask:
1921   case X86::BI__builtin_ia32_rndscalepd_128_mask:
1922   case X86::BI__builtin_ia32_rndscaleps_256_mask:
1923   case X86::BI__builtin_ia32_rndscalepd_256_mask:
1924   case X86::BI__builtin_ia32_rndscaleps_mask:
1925   case X86::BI__builtin_ia32_rndscalepd_mask:
1926   case X86::BI__builtin_ia32_reducepd128_mask:
1927   case X86::BI__builtin_ia32_reducepd256_mask:
1928   case X86::BI__builtin_ia32_reducepd512_mask:
1929   case X86::BI__builtin_ia32_reduceps128_mask:
1930   case X86::BI__builtin_ia32_reduceps256_mask:
1931   case X86::BI__builtin_ia32_reduceps512_mask:
1932   case X86::BI__builtin_ia32_prold512_mask:
1933   case X86::BI__builtin_ia32_prolq512_mask:
1934   case X86::BI__builtin_ia32_prold128_mask:
1935   case X86::BI__builtin_ia32_prold256_mask:
1936   case X86::BI__builtin_ia32_prolq128_mask:
1937   case X86::BI__builtin_ia32_prolq256_mask:
1938   case X86::BI__builtin_ia32_prord128_mask:
1939   case X86::BI__builtin_ia32_prord256_mask:
1940   case X86::BI__builtin_ia32_prorq128_mask:
1941   case X86::BI__builtin_ia32_prorq256_mask:
1942   case X86::BI__builtin_ia32_psllwi512_mask:
1943   case X86::BI__builtin_ia32_psllwi128_mask:
1944   case X86::BI__builtin_ia32_psllwi256_mask:
1945   case X86::BI__builtin_ia32_psrldi128_mask:
1946   case X86::BI__builtin_ia32_psrldi256_mask:
1947   case X86::BI__builtin_ia32_psrldi512_mask:
1948   case X86::BI__builtin_ia32_psrlqi128_mask:
1949   case X86::BI__builtin_ia32_psrlqi256_mask:
1950   case X86::BI__builtin_ia32_psrlqi512_mask:
1951   case X86::BI__builtin_ia32_psrawi512_mask:
1952   case X86::BI__builtin_ia32_psrawi128_mask:
1953   case X86::BI__builtin_ia32_psrawi256_mask:
1954   case X86::BI__builtin_ia32_psrlwi512_mask:
1955   case X86::BI__builtin_ia32_psrlwi128_mask:
1956   case X86::BI__builtin_ia32_psrlwi256_mask:
1957   case X86::BI__builtin_ia32_psradi128_mask:
1958   case X86::BI__builtin_ia32_psradi256_mask:
1959   case X86::BI__builtin_ia32_psradi512_mask:
1960   case X86::BI__builtin_ia32_psraqi128_mask:
1961   case X86::BI__builtin_ia32_psraqi256_mask:
1962   case X86::BI__builtin_ia32_psraqi512_mask:
1963   case X86::BI__builtin_ia32_pslldi128_mask:
1964   case X86::BI__builtin_ia32_pslldi256_mask:
1965   case X86::BI__builtin_ia32_pslldi512_mask:
1966   case X86::BI__builtin_ia32_psllqi128_mask:
1967   case X86::BI__builtin_ia32_psllqi256_mask:
1968   case X86::BI__builtin_ia32_psllqi512_mask:
1969   case X86::BI__builtin_ia32_fpclasspd128_mask:
1970   case X86::BI__builtin_ia32_fpclasspd256_mask:
1971   case X86::BI__builtin_ia32_fpclassps128_mask:
1972   case X86::BI__builtin_ia32_fpclassps256_mask:
1973   case X86::BI__builtin_ia32_fpclassps512_mask:
1974   case X86::BI__builtin_ia32_fpclasspd512_mask:
1975   case X86::BI__builtin_ia32_fpclasssd_mask:
1976   case X86::BI__builtin_ia32_fpclassss_mask:
1977     i = 1; l = 0; u = 255;
1978     break;
1979   case X86::BI__builtin_ia32_palignr:
1980   case X86::BI__builtin_ia32_insertps128:
1981   case X86::BI__builtin_ia32_dpps:
1982   case X86::BI__builtin_ia32_dppd:
1983   case X86::BI__builtin_ia32_dpps256:
1984   case X86::BI__builtin_ia32_mpsadbw128:
1985   case X86::BI__builtin_ia32_mpsadbw256:
1986   case X86::BI__builtin_ia32_pcmpistrm128:
1987   case X86::BI__builtin_ia32_pcmpistri128:
1988   case X86::BI__builtin_ia32_pcmpistria128:
1989   case X86::BI__builtin_ia32_pcmpistric128:
1990   case X86::BI__builtin_ia32_pcmpistrio128:
1991   case X86::BI__builtin_ia32_pcmpistris128:
1992   case X86::BI__builtin_ia32_pcmpistriz128:
1993   case X86::BI__builtin_ia32_pclmulqdq128:
1994   case X86::BI__builtin_ia32_vperm2f128_pd256:
1995   case X86::BI__builtin_ia32_vperm2f128_ps256:
1996   case X86::BI__builtin_ia32_vperm2f128_si256:
1997   case X86::BI__builtin_ia32_permti256:
1998     i = 2; l = -128; u = 255;
1999     break;
2000   case X86::BI__builtin_ia32_palignr128:
2001   case X86::BI__builtin_ia32_palignr256:
2002   case X86::BI__builtin_ia32_palignr128_mask:
2003   case X86::BI__builtin_ia32_palignr256_mask:
2004   case X86::BI__builtin_ia32_palignr512_mask:
2005   case X86::BI__builtin_ia32_alignq512_mask:
2006   case X86::BI__builtin_ia32_alignd512_mask:
2007   case X86::BI__builtin_ia32_alignd128_mask:
2008   case X86::BI__builtin_ia32_alignd256_mask:
2009   case X86::BI__builtin_ia32_alignq128_mask:
2010   case X86::BI__builtin_ia32_alignq256_mask:
2011   case X86::BI__builtin_ia32_vcomisd:
2012   case X86::BI__builtin_ia32_vcomiss:
2013   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2014   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2015   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2016   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2017   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2018   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2019   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2020     i = 2; l = 0; u = 255;
2021     break;
2022   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2023   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2024   case X86::BI__builtin_ia32_fixupimmps512_mask:
2025   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2026   case X86::BI__builtin_ia32_fixupimmsd_mask:
2027   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2028   case X86::BI__builtin_ia32_fixupimmss_mask:
2029   case X86::BI__builtin_ia32_fixupimmss_maskz:
2030   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2031   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2032   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2033   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2034   case X86::BI__builtin_ia32_fixupimmps128_mask:
2035   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2036   case X86::BI__builtin_ia32_fixupimmps256_mask:
2037   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2038   case X86::BI__builtin_ia32_pternlogd512_mask:
2039   case X86::BI__builtin_ia32_pternlogd512_maskz:
2040   case X86::BI__builtin_ia32_pternlogq512_mask:
2041   case X86::BI__builtin_ia32_pternlogq512_maskz:
2042   case X86::BI__builtin_ia32_pternlogd128_mask:
2043   case X86::BI__builtin_ia32_pternlogd128_maskz:
2044   case X86::BI__builtin_ia32_pternlogd256_mask:
2045   case X86::BI__builtin_ia32_pternlogd256_maskz:
2046   case X86::BI__builtin_ia32_pternlogq128_mask:
2047   case X86::BI__builtin_ia32_pternlogq128_maskz:
2048   case X86::BI__builtin_ia32_pternlogq256_mask:
2049   case X86::BI__builtin_ia32_pternlogq256_maskz:
2050     i = 3; l = 0; u = 255;
2051     break;
2052   case X86::BI__builtin_ia32_pcmpestrm128:
2053   case X86::BI__builtin_ia32_pcmpestri128:
2054   case X86::BI__builtin_ia32_pcmpestria128:
2055   case X86::BI__builtin_ia32_pcmpestric128:
2056   case X86::BI__builtin_ia32_pcmpestrio128:
2057   case X86::BI__builtin_ia32_pcmpestris128:
2058   case X86::BI__builtin_ia32_pcmpestriz128:
2059     i = 4; l = -128; u = 255;
2060     break;
2061   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2062   case X86::BI__builtin_ia32_rndscaless_round_mask:
2063     i = 4; l = 0; u = 255;
2064     break;
2065   }
2066   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2067 }
2068 
2069 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2070 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2071 /// Returns true when the format fits the function and the FormatStringInfo has
2072 /// been populated.
2073 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2074                                FormatStringInfo *FSI) {
2075   FSI->HasVAListArg = Format->getFirstArg() == 0;
2076   FSI->FormatIdx = Format->getFormatIdx() - 1;
2077   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2078 
2079   // The way the format attribute works in GCC, the implicit this argument
2080   // of member functions is counted. However, it doesn't appear in our own
2081   // lists, so decrement format_idx in that case.
2082   if (IsCXXMember) {
2083     if(FSI->FormatIdx == 0)
2084       return false;
2085     --FSI->FormatIdx;
2086     if (FSI->FirstDataArg != 0)
2087       --FSI->FirstDataArg;
2088   }
2089   return true;
2090 }
2091 
2092 /// Checks if a the given expression evaluates to null.
2093 ///
2094 /// \brief Returns true if the value evaluates to null.
2095 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2096   // If the expression has non-null type, it doesn't evaluate to null.
2097   if (auto nullability
2098         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2099     if (*nullability == NullabilityKind::NonNull)
2100       return false;
2101   }
2102 
2103   // As a special case, transparent unions initialized with zero are
2104   // considered null for the purposes of the nonnull attribute.
2105   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2106     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2107       if (const CompoundLiteralExpr *CLE =
2108           dyn_cast<CompoundLiteralExpr>(Expr))
2109         if (const InitListExpr *ILE =
2110             dyn_cast<InitListExpr>(CLE->getInitializer()))
2111           Expr = ILE->getInit(0);
2112   }
2113 
2114   bool Result;
2115   return (!Expr->isValueDependent() &&
2116           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2117           !Result);
2118 }
2119 
2120 static void CheckNonNullArgument(Sema &S,
2121                                  const Expr *ArgExpr,
2122                                  SourceLocation CallSiteLoc) {
2123   if (CheckNonNullExpr(S, ArgExpr))
2124     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2125            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2126 }
2127 
2128 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2129   FormatStringInfo FSI;
2130   if ((GetFormatStringType(Format) == FST_NSString) &&
2131       getFormatStringInfo(Format, false, &FSI)) {
2132     Idx = FSI.FormatIdx;
2133     return true;
2134   }
2135   return false;
2136 }
2137 /// \brief Diagnose use of %s directive in an NSString which is being passed
2138 /// as formatting string to formatting method.
2139 static void
2140 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2141                                         const NamedDecl *FDecl,
2142                                         Expr **Args,
2143                                         unsigned NumArgs) {
2144   unsigned Idx = 0;
2145   bool Format = false;
2146   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2147   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2148     Idx = 2;
2149     Format = true;
2150   }
2151   else
2152     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2153       if (S.GetFormatNSStringIdx(I, Idx)) {
2154         Format = true;
2155         break;
2156       }
2157     }
2158   if (!Format || NumArgs <= Idx)
2159     return;
2160   const Expr *FormatExpr = Args[Idx];
2161   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2162     FormatExpr = CSCE->getSubExpr();
2163   const StringLiteral *FormatString;
2164   if (const ObjCStringLiteral *OSL =
2165       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2166     FormatString = OSL->getString();
2167   else
2168     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2169   if (!FormatString)
2170     return;
2171   if (S.FormatStringHasSArg(FormatString)) {
2172     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2173       << "%s" << 1 << 1;
2174     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2175       << FDecl->getDeclName();
2176   }
2177 }
2178 
2179 /// Determine whether the given type has a non-null nullability annotation.
2180 static bool isNonNullType(ASTContext &ctx, QualType type) {
2181   if (auto nullability = type->getNullability(ctx))
2182     return *nullability == NullabilityKind::NonNull;
2183 
2184   return false;
2185 }
2186 
2187 static void CheckNonNullArguments(Sema &S,
2188                                   const NamedDecl *FDecl,
2189                                   const FunctionProtoType *Proto,
2190                                   ArrayRef<const Expr *> Args,
2191                                   SourceLocation CallSiteLoc) {
2192   assert((FDecl || Proto) && "Need a function declaration or prototype");
2193 
2194   // Check the attributes attached to the method/function itself.
2195   llvm::SmallBitVector NonNullArgs;
2196   if (FDecl) {
2197     // Handle the nonnull attribute on the function/method declaration itself.
2198     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2199       if (!NonNull->args_size()) {
2200         // Easy case: all pointer arguments are nonnull.
2201         for (const auto *Arg : Args)
2202           if (S.isValidPointerAttrType(Arg->getType()))
2203             CheckNonNullArgument(S, Arg, CallSiteLoc);
2204         return;
2205       }
2206 
2207       for (unsigned Val : NonNull->args()) {
2208         if (Val >= Args.size())
2209           continue;
2210         if (NonNullArgs.empty())
2211           NonNullArgs.resize(Args.size());
2212         NonNullArgs.set(Val);
2213       }
2214     }
2215   }
2216 
2217   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2218     // Handle the nonnull attribute on the parameters of the
2219     // function/method.
2220     ArrayRef<ParmVarDecl*> parms;
2221     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2222       parms = FD->parameters();
2223     else
2224       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2225 
2226     unsigned ParamIndex = 0;
2227     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2228          I != E; ++I, ++ParamIndex) {
2229       const ParmVarDecl *PVD = *I;
2230       if (PVD->hasAttr<NonNullAttr>() ||
2231           isNonNullType(S.Context, PVD->getType())) {
2232         if (NonNullArgs.empty())
2233           NonNullArgs.resize(Args.size());
2234 
2235         NonNullArgs.set(ParamIndex);
2236       }
2237     }
2238   } else {
2239     // If we have a non-function, non-method declaration but no
2240     // function prototype, try to dig out the function prototype.
2241     if (!Proto) {
2242       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2243         QualType type = VD->getType().getNonReferenceType();
2244         if (auto pointerType = type->getAs<PointerType>())
2245           type = pointerType->getPointeeType();
2246         else if (auto blockType = type->getAs<BlockPointerType>())
2247           type = blockType->getPointeeType();
2248         // FIXME: data member pointers?
2249 
2250         // Dig out the function prototype, if there is one.
2251         Proto = type->getAs<FunctionProtoType>();
2252       }
2253     }
2254 
2255     // Fill in non-null argument information from the nullability
2256     // information on the parameter types (if we have them).
2257     if (Proto) {
2258       unsigned Index = 0;
2259       for (auto paramType : Proto->getParamTypes()) {
2260         if (isNonNullType(S.Context, paramType)) {
2261           if (NonNullArgs.empty())
2262             NonNullArgs.resize(Args.size());
2263 
2264           NonNullArgs.set(Index);
2265         }
2266 
2267         ++Index;
2268       }
2269     }
2270   }
2271 
2272   // Check for non-null arguments.
2273   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2274        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2275     if (NonNullArgs[ArgIndex])
2276       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2277   }
2278 }
2279 
2280 /// Handles the checks for format strings, non-POD arguments to vararg
2281 /// functions, and NULL arguments passed to non-NULL parameters.
2282 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2283                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
2284                      SourceLocation Loc, SourceRange Range,
2285                      VariadicCallType CallType) {
2286   // FIXME: We should check as much as we can in the template definition.
2287   if (CurContext->isDependentContext())
2288     return;
2289 
2290   // Printf and scanf checking.
2291   llvm::SmallBitVector CheckedVarArgs;
2292   if (FDecl) {
2293     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2294       // Only create vector if there are format attributes.
2295       CheckedVarArgs.resize(Args.size());
2296 
2297       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2298                            CheckedVarArgs);
2299     }
2300   }
2301 
2302   // Refuse POD arguments that weren't caught by the format string
2303   // checks above.
2304   if (CallType != VariadicDoesNotApply) {
2305     unsigned NumParams = Proto ? Proto->getNumParams()
2306                        : FDecl && isa<FunctionDecl>(FDecl)
2307                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2308                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2309                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2310                        : 0;
2311 
2312     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2313       // Args[ArgIdx] can be null in malformed code.
2314       if (const Expr *Arg = Args[ArgIdx]) {
2315         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2316           checkVariadicArgument(Arg, CallType);
2317       }
2318     }
2319   }
2320 
2321   if (FDecl || Proto) {
2322     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2323 
2324     // Type safety checking.
2325     if (FDecl) {
2326       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2327         CheckArgumentWithTypeTag(I, Args.data());
2328     }
2329   }
2330 }
2331 
2332 /// CheckConstructorCall - Check a constructor call for correctness and safety
2333 /// properties not enforced by the C type system.
2334 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2335                                 ArrayRef<const Expr *> Args,
2336                                 const FunctionProtoType *Proto,
2337                                 SourceLocation Loc) {
2338   VariadicCallType CallType =
2339     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2340   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
2341             CallType);
2342 }
2343 
2344 /// CheckFunctionCall - Check a direct function call for various correctness
2345 /// and safety properties not strictly enforced by the C type system.
2346 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2347                              const FunctionProtoType *Proto) {
2348   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2349                               isa<CXXMethodDecl>(FDecl);
2350   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2351                           IsMemberOperatorCall;
2352   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2353                                                   TheCall->getCallee());
2354   Expr** Args = TheCall->getArgs();
2355   unsigned NumArgs = TheCall->getNumArgs();
2356   if (IsMemberOperatorCall) {
2357     // If this is a call to a member operator, hide the first argument
2358     // from checkCall.
2359     // FIXME: Our choice of AST representation here is less than ideal.
2360     ++Args;
2361     --NumArgs;
2362   }
2363   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
2364             IsMemberFunction, TheCall->getRParenLoc(),
2365             TheCall->getCallee()->getSourceRange(), CallType);
2366 
2367   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2368   // None of the checks below are needed for functions that don't have
2369   // simple names (e.g., C++ conversion functions).
2370   if (!FnInfo)
2371     return false;
2372 
2373   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
2374   if (getLangOpts().ObjC1)
2375     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2376 
2377   unsigned CMId = FDecl->getMemoryFunctionKind();
2378   if (CMId == 0)
2379     return false;
2380 
2381   // Handle memory setting and copying functions.
2382   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2383     CheckStrlcpycatArguments(TheCall, FnInfo);
2384   else if (CMId == Builtin::BIstrncat)
2385     CheckStrncatArguments(TheCall, FnInfo);
2386   else
2387     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2388 
2389   return false;
2390 }
2391 
2392 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2393                                ArrayRef<const Expr *> Args) {
2394   VariadicCallType CallType =
2395       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2396 
2397   checkCall(Method, nullptr, Args,
2398             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2399             CallType);
2400 
2401   return false;
2402 }
2403 
2404 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2405                             const FunctionProtoType *Proto) {
2406   QualType Ty;
2407   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2408     Ty = V->getType().getNonReferenceType();
2409   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2410     Ty = F->getType().getNonReferenceType();
2411   else
2412     return false;
2413 
2414   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2415       !Ty->isFunctionProtoType())
2416     return false;
2417 
2418   VariadicCallType CallType;
2419   if (!Proto || !Proto->isVariadic()) {
2420     CallType = VariadicDoesNotApply;
2421   } else if (Ty->isBlockPointerType()) {
2422     CallType = VariadicBlock;
2423   } else { // Ty->isFunctionPointerType()
2424     CallType = VariadicFunction;
2425   }
2426 
2427   checkCall(NDecl, Proto,
2428             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2429             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2430             TheCall->getCallee()->getSourceRange(), CallType);
2431 
2432   return false;
2433 }
2434 
2435 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2436 /// such as function pointers returned from functions.
2437 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2438   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2439                                                   TheCall->getCallee());
2440   checkCall(/*FDecl=*/nullptr, Proto,
2441             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2442             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2443             TheCall->getCallee()->getSourceRange(), CallType);
2444 
2445   return false;
2446 }
2447 
2448 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2449   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2450     return false;
2451 
2452   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2453   switch (Op) {
2454   case AtomicExpr::AO__c11_atomic_init:
2455     llvm_unreachable("There is no ordering argument for an init");
2456 
2457   case AtomicExpr::AO__c11_atomic_load:
2458   case AtomicExpr::AO__atomic_load_n:
2459   case AtomicExpr::AO__atomic_load:
2460     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2461            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2462 
2463   case AtomicExpr::AO__c11_atomic_store:
2464   case AtomicExpr::AO__atomic_store:
2465   case AtomicExpr::AO__atomic_store_n:
2466     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2467            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2468            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2469 
2470   default:
2471     return true;
2472   }
2473 }
2474 
2475 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2476                                          AtomicExpr::AtomicOp Op) {
2477   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2478   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2479 
2480   // All these operations take one of the following forms:
2481   enum {
2482     // C    __c11_atomic_init(A *, C)
2483     Init,
2484     // C    __c11_atomic_load(A *, int)
2485     Load,
2486     // void __atomic_load(A *, CP, int)
2487     LoadCopy,
2488     // void __atomic_store(A *, CP, int)
2489     Copy,
2490     // C    __c11_atomic_add(A *, M, int)
2491     Arithmetic,
2492     // C    __atomic_exchange_n(A *, CP, int)
2493     Xchg,
2494     // void __atomic_exchange(A *, C *, CP, int)
2495     GNUXchg,
2496     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2497     C11CmpXchg,
2498     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2499     GNUCmpXchg
2500   } Form = Init;
2501   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2502   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2503   // where:
2504   //   C is an appropriate type,
2505   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2506   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2507   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2508   //   the int parameters are for orderings.
2509 
2510   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2511                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2512                         AtomicExpr::AO__atomic_load,
2513                 "need to update code for modified C11 atomics");
2514   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2515                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2516   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2517              Op == AtomicExpr::AO__atomic_store_n ||
2518              Op == AtomicExpr::AO__atomic_exchange_n ||
2519              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2520   bool IsAddSub = false;
2521 
2522   switch (Op) {
2523   case AtomicExpr::AO__c11_atomic_init:
2524     Form = Init;
2525     break;
2526 
2527   case AtomicExpr::AO__c11_atomic_load:
2528   case AtomicExpr::AO__atomic_load_n:
2529     Form = Load;
2530     break;
2531 
2532   case AtomicExpr::AO__atomic_load:
2533     Form = LoadCopy;
2534     break;
2535 
2536   case AtomicExpr::AO__c11_atomic_store:
2537   case AtomicExpr::AO__atomic_store:
2538   case AtomicExpr::AO__atomic_store_n:
2539     Form = Copy;
2540     break;
2541 
2542   case AtomicExpr::AO__c11_atomic_fetch_add:
2543   case AtomicExpr::AO__c11_atomic_fetch_sub:
2544   case AtomicExpr::AO__atomic_fetch_add:
2545   case AtomicExpr::AO__atomic_fetch_sub:
2546   case AtomicExpr::AO__atomic_add_fetch:
2547   case AtomicExpr::AO__atomic_sub_fetch:
2548     IsAddSub = true;
2549     // Fall through.
2550   case AtomicExpr::AO__c11_atomic_fetch_and:
2551   case AtomicExpr::AO__c11_atomic_fetch_or:
2552   case AtomicExpr::AO__c11_atomic_fetch_xor:
2553   case AtomicExpr::AO__atomic_fetch_and:
2554   case AtomicExpr::AO__atomic_fetch_or:
2555   case AtomicExpr::AO__atomic_fetch_xor:
2556   case AtomicExpr::AO__atomic_fetch_nand:
2557   case AtomicExpr::AO__atomic_and_fetch:
2558   case AtomicExpr::AO__atomic_or_fetch:
2559   case AtomicExpr::AO__atomic_xor_fetch:
2560   case AtomicExpr::AO__atomic_nand_fetch:
2561     Form = Arithmetic;
2562     break;
2563 
2564   case AtomicExpr::AO__c11_atomic_exchange:
2565   case AtomicExpr::AO__atomic_exchange_n:
2566     Form = Xchg;
2567     break;
2568 
2569   case AtomicExpr::AO__atomic_exchange:
2570     Form = GNUXchg;
2571     break;
2572 
2573   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2574   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2575     Form = C11CmpXchg;
2576     break;
2577 
2578   case AtomicExpr::AO__atomic_compare_exchange:
2579   case AtomicExpr::AO__atomic_compare_exchange_n:
2580     Form = GNUCmpXchg;
2581     break;
2582   }
2583 
2584   // Check we have the right number of arguments.
2585   if (TheCall->getNumArgs() < NumArgs[Form]) {
2586     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2587       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2588       << TheCall->getCallee()->getSourceRange();
2589     return ExprError();
2590   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
2591     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
2592          diag::err_typecheck_call_too_many_args)
2593       << 0 << NumArgs[Form] << TheCall->getNumArgs()
2594       << TheCall->getCallee()->getSourceRange();
2595     return ExprError();
2596   }
2597 
2598   // Inspect the first argument of the atomic operation.
2599   Expr *Ptr = TheCall->getArg(0);
2600   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2601   if (ConvertedPtr.isInvalid())
2602     return ExprError();
2603 
2604   Ptr = ConvertedPtr.get();
2605   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
2606   if (!pointerType) {
2607     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2608       << Ptr->getType() << Ptr->getSourceRange();
2609     return ExprError();
2610   }
2611 
2612   // For a __c11 builtin, this should be a pointer to an _Atomic type.
2613   QualType AtomTy = pointerType->getPointeeType(); // 'A'
2614   QualType ValType = AtomTy; // 'C'
2615   if (IsC11) {
2616     if (!AtomTy->isAtomicType()) {
2617       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2618         << Ptr->getType() << Ptr->getSourceRange();
2619       return ExprError();
2620     }
2621     if (AtomTy.isConstQualified()) {
2622       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2623         << Ptr->getType() << Ptr->getSourceRange();
2624       return ExprError();
2625     }
2626     ValType = AtomTy->getAs<AtomicType>()->getValueType();
2627   } else if (Form != Load && Form != LoadCopy) {
2628     if (ValType.isConstQualified()) {
2629       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2630         << Ptr->getType() << Ptr->getSourceRange();
2631       return ExprError();
2632     }
2633   }
2634 
2635   // For an arithmetic operation, the implied arithmetic must be well-formed.
2636   if (Form == Arithmetic) {
2637     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
2638     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
2639       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2640         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2641       return ExprError();
2642     }
2643     if (!IsAddSub && !ValType->isIntegerType()) {
2644       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2645         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2646       return ExprError();
2647     }
2648     if (IsC11 && ValType->isPointerType() &&
2649         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
2650                             diag::err_incomplete_type)) {
2651       return ExprError();
2652     }
2653   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
2654     // For __atomic_*_n operations, the value type must be a scalar integral or
2655     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
2656     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2657       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
2658     return ExprError();
2659   }
2660 
2661   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2662       !AtomTy->isScalarType()) {
2663     // For GNU atomics, require a trivially-copyable type. This is not part of
2664     // the GNU atomics specification, but we enforce it for sanity.
2665     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2666       << Ptr->getType() << Ptr->getSourceRange();
2667     return ExprError();
2668   }
2669 
2670   switch (ValType.getObjCLifetime()) {
2671   case Qualifiers::OCL_None:
2672   case Qualifiers::OCL_ExplicitNone:
2673     // okay
2674     break;
2675 
2676   case Qualifiers::OCL_Weak:
2677   case Qualifiers::OCL_Strong:
2678   case Qualifiers::OCL_Autoreleasing:
2679     // FIXME: Can this happen? By this point, ValType should be known
2680     // to be trivially copyable.
2681     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2682       << ValType << Ptr->getSourceRange();
2683     return ExprError();
2684   }
2685 
2686   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2687   // volatile-ness of the pointee-type inject itself into the result or the
2688   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2689   ValType.removeLocalVolatile();
2690   ValType.removeLocalConst();
2691   QualType ResultType = ValType;
2692   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2693     ResultType = Context.VoidTy;
2694   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2695     ResultType = Context.BoolTy;
2696 
2697   // The type of a parameter passed 'by value'. In the GNU atomics, such
2698   // arguments are actually passed as pointers.
2699   QualType ByValType = ValType; // 'CP'
2700   if (!IsC11 && !IsN)
2701     ByValType = Ptr->getType();
2702 
2703   // The first argument --- the pointer --- has a fixed type; we
2704   // deduce the types of the rest of the arguments accordingly.  Walk
2705   // the remaining arguments, converting them to the deduced value type.
2706   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2707     QualType Ty;
2708     if (i < NumVals[Form] + 1) {
2709       switch (i) {
2710       case 1:
2711         // The second argument is the non-atomic operand. For arithmetic, this
2712         // is always passed by value, and for a compare_exchange it is always
2713         // passed by address. For the rest, GNU uses by-address and C11 uses
2714         // by-value.
2715         assert(Form != Load);
2716         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2717           Ty = ValType;
2718         else if (Form == Copy || Form == Xchg)
2719           Ty = ByValType;
2720         else if (Form == Arithmetic)
2721           Ty = Context.getPointerDiffType();
2722         else {
2723           Expr *ValArg = TheCall->getArg(i);
2724           unsigned AS = 0;
2725           // Keep address space of non-atomic pointer type.
2726           if (const PointerType *PtrTy =
2727                   ValArg->getType()->getAs<PointerType>()) {
2728             AS = PtrTy->getPointeeType().getAddressSpace();
2729           }
2730           Ty = Context.getPointerType(
2731               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2732         }
2733         break;
2734       case 2:
2735         // The third argument to compare_exchange / GNU exchange is a
2736         // (pointer to a) desired value.
2737         Ty = ByValType;
2738         break;
2739       case 3:
2740         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2741         Ty = Context.BoolTy;
2742         break;
2743       }
2744     } else {
2745       // The order(s) are always converted to int.
2746       Ty = Context.IntTy;
2747     }
2748 
2749     InitializedEntity Entity =
2750         InitializedEntity::InitializeParameter(Context, Ty, false);
2751     ExprResult Arg = TheCall->getArg(i);
2752     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2753     if (Arg.isInvalid())
2754       return true;
2755     TheCall->setArg(i, Arg.get());
2756   }
2757 
2758   // Permute the arguments into a 'consistent' order.
2759   SmallVector<Expr*, 5> SubExprs;
2760   SubExprs.push_back(Ptr);
2761   switch (Form) {
2762   case Init:
2763     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2764     SubExprs.push_back(TheCall->getArg(1)); // Val1
2765     break;
2766   case Load:
2767     SubExprs.push_back(TheCall->getArg(1)); // Order
2768     break;
2769   case LoadCopy:
2770   case Copy:
2771   case Arithmetic:
2772   case Xchg:
2773     SubExprs.push_back(TheCall->getArg(2)); // Order
2774     SubExprs.push_back(TheCall->getArg(1)); // Val1
2775     break;
2776   case GNUXchg:
2777     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2778     SubExprs.push_back(TheCall->getArg(3)); // Order
2779     SubExprs.push_back(TheCall->getArg(1)); // Val1
2780     SubExprs.push_back(TheCall->getArg(2)); // Val2
2781     break;
2782   case C11CmpXchg:
2783     SubExprs.push_back(TheCall->getArg(3)); // Order
2784     SubExprs.push_back(TheCall->getArg(1)); // Val1
2785     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2786     SubExprs.push_back(TheCall->getArg(2)); // Val2
2787     break;
2788   case GNUCmpXchg:
2789     SubExprs.push_back(TheCall->getArg(4)); // Order
2790     SubExprs.push_back(TheCall->getArg(1)); // Val1
2791     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2792     SubExprs.push_back(TheCall->getArg(2)); // Val2
2793     SubExprs.push_back(TheCall->getArg(3)); // Weak
2794     break;
2795   }
2796 
2797   if (SubExprs.size() >= 2 && Form != Init) {
2798     llvm::APSInt Result(32);
2799     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2800         !isValidOrderingForOp(Result.getSExtValue(), Op))
2801       Diag(SubExprs[1]->getLocStart(),
2802            diag::warn_atomic_op_has_invalid_memory_order)
2803           << SubExprs[1]->getSourceRange();
2804   }
2805 
2806   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2807                                             SubExprs, ResultType, Op,
2808                                             TheCall->getRParenLoc());
2809 
2810   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2811        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2812       Context.AtomicUsesUnsupportedLibcall(AE))
2813     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2814     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2815 
2816   return AE;
2817 }
2818 
2819 /// checkBuiltinArgument - Given a call to a builtin function, perform
2820 /// normal type-checking on the given argument, updating the call in
2821 /// place.  This is useful when a builtin function requires custom
2822 /// type-checking for some of its arguments but not necessarily all of
2823 /// them.
2824 ///
2825 /// Returns true on error.
2826 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2827   FunctionDecl *Fn = E->getDirectCallee();
2828   assert(Fn && "builtin call without direct callee!");
2829 
2830   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2831   InitializedEntity Entity =
2832     InitializedEntity::InitializeParameter(S.Context, Param);
2833 
2834   ExprResult Arg = E->getArg(0);
2835   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2836   if (Arg.isInvalid())
2837     return true;
2838 
2839   E->setArg(ArgIndex, Arg.get());
2840   return false;
2841 }
2842 
2843 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2844 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2845 /// type of its first argument.  The main ActOnCallExpr routines have already
2846 /// promoted the types of arguments because all of these calls are prototyped as
2847 /// void(...).
2848 ///
2849 /// This function goes through and does final semantic checking for these
2850 /// builtins,
2851 ExprResult
2852 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2853   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2854   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2855   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2856 
2857   // Ensure that we have at least one argument to do type inference from.
2858   if (TheCall->getNumArgs() < 1) {
2859     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2860       << 0 << 1 << TheCall->getNumArgs()
2861       << TheCall->getCallee()->getSourceRange();
2862     return ExprError();
2863   }
2864 
2865   // Inspect the first argument of the atomic builtin.  This should always be
2866   // a pointer type, whose element is an integral scalar or pointer type.
2867   // Because it is a pointer type, we don't have to worry about any implicit
2868   // casts here.
2869   // FIXME: We don't allow floating point scalars as input.
2870   Expr *FirstArg = TheCall->getArg(0);
2871   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2872   if (FirstArgResult.isInvalid())
2873     return ExprError();
2874   FirstArg = FirstArgResult.get();
2875   TheCall->setArg(0, FirstArg);
2876 
2877   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2878   if (!pointerType) {
2879     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2880       << FirstArg->getType() << FirstArg->getSourceRange();
2881     return ExprError();
2882   }
2883 
2884   QualType ValType = pointerType->getPointeeType();
2885   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2886       !ValType->isBlockPointerType()) {
2887     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2888       << FirstArg->getType() << FirstArg->getSourceRange();
2889     return ExprError();
2890   }
2891 
2892   switch (ValType.getObjCLifetime()) {
2893   case Qualifiers::OCL_None:
2894   case Qualifiers::OCL_ExplicitNone:
2895     // okay
2896     break;
2897 
2898   case Qualifiers::OCL_Weak:
2899   case Qualifiers::OCL_Strong:
2900   case Qualifiers::OCL_Autoreleasing:
2901     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2902       << ValType << FirstArg->getSourceRange();
2903     return ExprError();
2904   }
2905 
2906   // Strip any qualifiers off ValType.
2907   ValType = ValType.getUnqualifiedType();
2908 
2909   // The majority of builtins return a value, but a few have special return
2910   // types, so allow them to override appropriately below.
2911   QualType ResultType = ValType;
2912 
2913   // We need to figure out which concrete builtin this maps onto.  For example,
2914   // __sync_fetch_and_add with a 2 byte object turns into
2915   // __sync_fetch_and_add_2.
2916 #define BUILTIN_ROW(x) \
2917   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2918     Builtin::BI##x##_8, Builtin::BI##x##_16 }
2919 
2920   static const unsigned BuiltinIndices[][5] = {
2921     BUILTIN_ROW(__sync_fetch_and_add),
2922     BUILTIN_ROW(__sync_fetch_and_sub),
2923     BUILTIN_ROW(__sync_fetch_and_or),
2924     BUILTIN_ROW(__sync_fetch_and_and),
2925     BUILTIN_ROW(__sync_fetch_and_xor),
2926     BUILTIN_ROW(__sync_fetch_and_nand),
2927 
2928     BUILTIN_ROW(__sync_add_and_fetch),
2929     BUILTIN_ROW(__sync_sub_and_fetch),
2930     BUILTIN_ROW(__sync_and_and_fetch),
2931     BUILTIN_ROW(__sync_or_and_fetch),
2932     BUILTIN_ROW(__sync_xor_and_fetch),
2933     BUILTIN_ROW(__sync_nand_and_fetch),
2934 
2935     BUILTIN_ROW(__sync_val_compare_and_swap),
2936     BUILTIN_ROW(__sync_bool_compare_and_swap),
2937     BUILTIN_ROW(__sync_lock_test_and_set),
2938     BUILTIN_ROW(__sync_lock_release),
2939     BUILTIN_ROW(__sync_swap)
2940   };
2941 #undef BUILTIN_ROW
2942 
2943   // Determine the index of the size.
2944   unsigned SizeIndex;
2945   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2946   case 1: SizeIndex = 0; break;
2947   case 2: SizeIndex = 1; break;
2948   case 4: SizeIndex = 2; break;
2949   case 8: SizeIndex = 3; break;
2950   case 16: SizeIndex = 4; break;
2951   default:
2952     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2953       << FirstArg->getType() << FirstArg->getSourceRange();
2954     return ExprError();
2955   }
2956 
2957   // Each of these builtins has one pointer argument, followed by some number of
2958   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2959   // that we ignore.  Find out which row of BuiltinIndices to read from as well
2960   // as the number of fixed args.
2961   unsigned BuiltinID = FDecl->getBuiltinID();
2962   unsigned BuiltinIndex, NumFixed = 1;
2963   bool WarnAboutSemanticsChange = false;
2964   switch (BuiltinID) {
2965   default: llvm_unreachable("Unknown overloaded atomic builtin!");
2966   case Builtin::BI__sync_fetch_and_add:
2967   case Builtin::BI__sync_fetch_and_add_1:
2968   case Builtin::BI__sync_fetch_and_add_2:
2969   case Builtin::BI__sync_fetch_and_add_4:
2970   case Builtin::BI__sync_fetch_and_add_8:
2971   case Builtin::BI__sync_fetch_and_add_16:
2972     BuiltinIndex = 0;
2973     break;
2974 
2975   case Builtin::BI__sync_fetch_and_sub:
2976   case Builtin::BI__sync_fetch_and_sub_1:
2977   case Builtin::BI__sync_fetch_and_sub_2:
2978   case Builtin::BI__sync_fetch_and_sub_4:
2979   case Builtin::BI__sync_fetch_and_sub_8:
2980   case Builtin::BI__sync_fetch_and_sub_16:
2981     BuiltinIndex = 1;
2982     break;
2983 
2984   case Builtin::BI__sync_fetch_and_or:
2985   case Builtin::BI__sync_fetch_and_or_1:
2986   case Builtin::BI__sync_fetch_and_or_2:
2987   case Builtin::BI__sync_fetch_and_or_4:
2988   case Builtin::BI__sync_fetch_and_or_8:
2989   case Builtin::BI__sync_fetch_and_or_16:
2990     BuiltinIndex = 2;
2991     break;
2992 
2993   case Builtin::BI__sync_fetch_and_and:
2994   case Builtin::BI__sync_fetch_and_and_1:
2995   case Builtin::BI__sync_fetch_and_and_2:
2996   case Builtin::BI__sync_fetch_and_and_4:
2997   case Builtin::BI__sync_fetch_and_and_8:
2998   case Builtin::BI__sync_fetch_and_and_16:
2999     BuiltinIndex = 3;
3000     break;
3001 
3002   case Builtin::BI__sync_fetch_and_xor:
3003   case Builtin::BI__sync_fetch_and_xor_1:
3004   case Builtin::BI__sync_fetch_and_xor_2:
3005   case Builtin::BI__sync_fetch_and_xor_4:
3006   case Builtin::BI__sync_fetch_and_xor_8:
3007   case Builtin::BI__sync_fetch_and_xor_16:
3008     BuiltinIndex = 4;
3009     break;
3010 
3011   case Builtin::BI__sync_fetch_and_nand:
3012   case Builtin::BI__sync_fetch_and_nand_1:
3013   case Builtin::BI__sync_fetch_and_nand_2:
3014   case Builtin::BI__sync_fetch_and_nand_4:
3015   case Builtin::BI__sync_fetch_and_nand_8:
3016   case Builtin::BI__sync_fetch_and_nand_16:
3017     BuiltinIndex = 5;
3018     WarnAboutSemanticsChange = true;
3019     break;
3020 
3021   case Builtin::BI__sync_add_and_fetch:
3022   case Builtin::BI__sync_add_and_fetch_1:
3023   case Builtin::BI__sync_add_and_fetch_2:
3024   case Builtin::BI__sync_add_and_fetch_4:
3025   case Builtin::BI__sync_add_and_fetch_8:
3026   case Builtin::BI__sync_add_and_fetch_16:
3027     BuiltinIndex = 6;
3028     break;
3029 
3030   case Builtin::BI__sync_sub_and_fetch:
3031   case Builtin::BI__sync_sub_and_fetch_1:
3032   case Builtin::BI__sync_sub_and_fetch_2:
3033   case Builtin::BI__sync_sub_and_fetch_4:
3034   case Builtin::BI__sync_sub_and_fetch_8:
3035   case Builtin::BI__sync_sub_and_fetch_16:
3036     BuiltinIndex = 7;
3037     break;
3038 
3039   case Builtin::BI__sync_and_and_fetch:
3040   case Builtin::BI__sync_and_and_fetch_1:
3041   case Builtin::BI__sync_and_and_fetch_2:
3042   case Builtin::BI__sync_and_and_fetch_4:
3043   case Builtin::BI__sync_and_and_fetch_8:
3044   case Builtin::BI__sync_and_and_fetch_16:
3045     BuiltinIndex = 8;
3046     break;
3047 
3048   case Builtin::BI__sync_or_and_fetch:
3049   case Builtin::BI__sync_or_and_fetch_1:
3050   case Builtin::BI__sync_or_and_fetch_2:
3051   case Builtin::BI__sync_or_and_fetch_4:
3052   case Builtin::BI__sync_or_and_fetch_8:
3053   case Builtin::BI__sync_or_and_fetch_16:
3054     BuiltinIndex = 9;
3055     break;
3056 
3057   case Builtin::BI__sync_xor_and_fetch:
3058   case Builtin::BI__sync_xor_and_fetch_1:
3059   case Builtin::BI__sync_xor_and_fetch_2:
3060   case Builtin::BI__sync_xor_and_fetch_4:
3061   case Builtin::BI__sync_xor_and_fetch_8:
3062   case Builtin::BI__sync_xor_and_fetch_16:
3063     BuiltinIndex = 10;
3064     break;
3065 
3066   case Builtin::BI__sync_nand_and_fetch:
3067   case Builtin::BI__sync_nand_and_fetch_1:
3068   case Builtin::BI__sync_nand_and_fetch_2:
3069   case Builtin::BI__sync_nand_and_fetch_4:
3070   case Builtin::BI__sync_nand_and_fetch_8:
3071   case Builtin::BI__sync_nand_and_fetch_16:
3072     BuiltinIndex = 11;
3073     WarnAboutSemanticsChange = true;
3074     break;
3075 
3076   case Builtin::BI__sync_val_compare_and_swap:
3077   case Builtin::BI__sync_val_compare_and_swap_1:
3078   case Builtin::BI__sync_val_compare_and_swap_2:
3079   case Builtin::BI__sync_val_compare_and_swap_4:
3080   case Builtin::BI__sync_val_compare_and_swap_8:
3081   case Builtin::BI__sync_val_compare_and_swap_16:
3082     BuiltinIndex = 12;
3083     NumFixed = 2;
3084     break;
3085 
3086   case Builtin::BI__sync_bool_compare_and_swap:
3087   case Builtin::BI__sync_bool_compare_and_swap_1:
3088   case Builtin::BI__sync_bool_compare_and_swap_2:
3089   case Builtin::BI__sync_bool_compare_and_swap_4:
3090   case Builtin::BI__sync_bool_compare_and_swap_8:
3091   case Builtin::BI__sync_bool_compare_and_swap_16:
3092     BuiltinIndex = 13;
3093     NumFixed = 2;
3094     ResultType = Context.BoolTy;
3095     break;
3096 
3097   case Builtin::BI__sync_lock_test_and_set:
3098   case Builtin::BI__sync_lock_test_and_set_1:
3099   case Builtin::BI__sync_lock_test_and_set_2:
3100   case Builtin::BI__sync_lock_test_and_set_4:
3101   case Builtin::BI__sync_lock_test_and_set_8:
3102   case Builtin::BI__sync_lock_test_and_set_16:
3103     BuiltinIndex = 14;
3104     break;
3105 
3106   case Builtin::BI__sync_lock_release:
3107   case Builtin::BI__sync_lock_release_1:
3108   case Builtin::BI__sync_lock_release_2:
3109   case Builtin::BI__sync_lock_release_4:
3110   case Builtin::BI__sync_lock_release_8:
3111   case Builtin::BI__sync_lock_release_16:
3112     BuiltinIndex = 15;
3113     NumFixed = 0;
3114     ResultType = Context.VoidTy;
3115     break;
3116 
3117   case Builtin::BI__sync_swap:
3118   case Builtin::BI__sync_swap_1:
3119   case Builtin::BI__sync_swap_2:
3120   case Builtin::BI__sync_swap_4:
3121   case Builtin::BI__sync_swap_8:
3122   case Builtin::BI__sync_swap_16:
3123     BuiltinIndex = 16;
3124     break;
3125   }
3126 
3127   // Now that we know how many fixed arguments we expect, first check that we
3128   // have at least that many.
3129   if (TheCall->getNumArgs() < 1+NumFixed) {
3130     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3131       << 0 << 1+NumFixed << TheCall->getNumArgs()
3132       << TheCall->getCallee()->getSourceRange();
3133     return ExprError();
3134   }
3135 
3136   if (WarnAboutSemanticsChange) {
3137     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3138       << TheCall->getCallee()->getSourceRange();
3139   }
3140 
3141   // Get the decl for the concrete builtin from this, we can tell what the
3142   // concrete integer type we should convert to is.
3143   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3144   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3145   FunctionDecl *NewBuiltinDecl;
3146   if (NewBuiltinID == BuiltinID)
3147     NewBuiltinDecl = FDecl;
3148   else {
3149     // Perform builtin lookup to avoid redeclaring it.
3150     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3151     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3152     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3153     assert(Res.getFoundDecl());
3154     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3155     if (!NewBuiltinDecl)
3156       return ExprError();
3157   }
3158 
3159   // The first argument --- the pointer --- has a fixed type; we
3160   // deduce the types of the rest of the arguments accordingly.  Walk
3161   // the remaining arguments, converting them to the deduced value type.
3162   for (unsigned i = 0; i != NumFixed; ++i) {
3163     ExprResult Arg = TheCall->getArg(i+1);
3164 
3165     // GCC does an implicit conversion to the pointer or integer ValType.  This
3166     // can fail in some cases (1i -> int**), check for this error case now.
3167     // Initialize the argument.
3168     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3169                                                    ValType, /*consume*/ false);
3170     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3171     if (Arg.isInvalid())
3172       return ExprError();
3173 
3174     // Okay, we have something that *can* be converted to the right type.  Check
3175     // to see if there is a potentially weird extension going on here.  This can
3176     // happen when you do an atomic operation on something like an char* and
3177     // pass in 42.  The 42 gets converted to char.  This is even more strange
3178     // for things like 45.123 -> char, etc.
3179     // FIXME: Do this check.
3180     TheCall->setArg(i+1, Arg.get());
3181   }
3182 
3183   ASTContext& Context = this->getASTContext();
3184 
3185   // Create a new DeclRefExpr to refer to the new decl.
3186   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3187       Context,
3188       DRE->getQualifierLoc(),
3189       SourceLocation(),
3190       NewBuiltinDecl,
3191       /*enclosing*/ false,
3192       DRE->getLocation(),
3193       Context.BuiltinFnTy,
3194       DRE->getValueKind());
3195 
3196   // Set the callee in the CallExpr.
3197   // FIXME: This loses syntactic information.
3198   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3199   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3200                                               CK_BuiltinFnToFnPtr);
3201   TheCall->setCallee(PromotedCall.get());
3202 
3203   // Change the result type of the call to match the original value type. This
3204   // is arbitrary, but the codegen for these builtins ins design to handle it
3205   // gracefully.
3206   TheCall->setType(ResultType);
3207 
3208   return TheCallResult;
3209 }
3210 
3211 /// SemaBuiltinNontemporalOverloaded - We have a call to
3212 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3213 /// overloaded function based on the pointer type of its last argument.
3214 ///
3215 /// This function goes through and does final semantic checking for these
3216 /// builtins.
3217 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3218   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3219   DeclRefExpr *DRE =
3220       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3221   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3222   unsigned BuiltinID = FDecl->getBuiltinID();
3223   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3224           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3225          "Unexpected nontemporal load/store builtin!");
3226   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3227   unsigned numArgs = isStore ? 2 : 1;
3228 
3229   // Ensure that we have the proper number of arguments.
3230   if (checkArgCount(*this, TheCall, numArgs))
3231     return ExprError();
3232 
3233   // Inspect the last argument of the nontemporal builtin.  This should always
3234   // be a pointer type, from which we imply the type of the memory access.
3235   // Because it is a pointer type, we don't have to worry about any implicit
3236   // casts here.
3237   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3238   ExprResult PointerArgResult =
3239       DefaultFunctionArrayLvalueConversion(PointerArg);
3240 
3241   if (PointerArgResult.isInvalid())
3242     return ExprError();
3243   PointerArg = PointerArgResult.get();
3244   TheCall->setArg(numArgs - 1, PointerArg);
3245 
3246   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3247   if (!pointerType) {
3248     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3249         << PointerArg->getType() << PointerArg->getSourceRange();
3250     return ExprError();
3251   }
3252 
3253   QualType ValType = pointerType->getPointeeType();
3254 
3255   // Strip any qualifiers off ValType.
3256   ValType = ValType.getUnqualifiedType();
3257   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3258       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3259       !ValType->isVectorType()) {
3260     Diag(DRE->getLocStart(),
3261          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3262         << PointerArg->getType() << PointerArg->getSourceRange();
3263     return ExprError();
3264   }
3265 
3266   if (!isStore) {
3267     TheCall->setType(ValType);
3268     return TheCallResult;
3269   }
3270 
3271   ExprResult ValArg = TheCall->getArg(0);
3272   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3273       Context, ValType, /*consume*/ false);
3274   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3275   if (ValArg.isInvalid())
3276     return ExprError();
3277 
3278   TheCall->setArg(0, ValArg.get());
3279   TheCall->setType(Context.VoidTy);
3280   return TheCallResult;
3281 }
3282 
3283 /// CheckObjCString - Checks that the argument to the builtin
3284 /// CFString constructor is correct
3285 /// Note: It might also make sense to do the UTF-16 conversion here (would
3286 /// simplify the backend).
3287 bool Sema::CheckObjCString(Expr *Arg) {
3288   Arg = Arg->IgnoreParenCasts();
3289   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3290 
3291   if (!Literal || !Literal->isAscii()) {
3292     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3293       << Arg->getSourceRange();
3294     return true;
3295   }
3296 
3297   if (Literal->containsNonAsciiOrNull()) {
3298     StringRef String = Literal->getString();
3299     unsigned NumBytes = String.size();
3300     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3301     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3302     llvm::UTF16 *ToPtr = &ToBuf[0];
3303 
3304     llvm::ConversionResult Result =
3305         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3306                                  ToPtr + NumBytes, llvm::strictConversion);
3307     // Check for conversion failure.
3308     if (Result != llvm::conversionOK)
3309       Diag(Arg->getLocStart(),
3310            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3311   }
3312   return false;
3313 }
3314 
3315 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3316 /// for validity.  Emit an error and return true on failure; return false
3317 /// on success.
3318 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
3319   Expr *Fn = TheCall->getCallee();
3320   if (TheCall->getNumArgs() > 2) {
3321     Diag(TheCall->getArg(2)->getLocStart(),
3322          diag::err_typecheck_call_too_many_args)
3323       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3324       << Fn->getSourceRange()
3325       << SourceRange(TheCall->getArg(2)->getLocStart(),
3326                      (*(TheCall->arg_end()-1))->getLocEnd());
3327     return true;
3328   }
3329 
3330   if (TheCall->getNumArgs() < 2) {
3331     return Diag(TheCall->getLocEnd(),
3332       diag::err_typecheck_call_too_few_args_at_least)
3333       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3334   }
3335 
3336   // Type-check the first argument normally.
3337   if (checkBuiltinArgument(*this, TheCall, 0))
3338     return true;
3339 
3340   // Determine whether the current function is variadic or not.
3341   BlockScopeInfo *CurBlock = getCurBlock();
3342   bool isVariadic;
3343   if (CurBlock)
3344     isVariadic = CurBlock->TheDecl->isVariadic();
3345   else if (FunctionDecl *FD = getCurFunctionDecl())
3346     isVariadic = FD->isVariadic();
3347   else
3348     isVariadic = getCurMethodDecl()->isVariadic();
3349 
3350   if (!isVariadic) {
3351     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3352     return true;
3353   }
3354 
3355   // Verify that the second argument to the builtin is the last argument of the
3356   // current function or method.
3357   bool SecondArgIsLastNamedArgument = false;
3358   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3359 
3360   // These are valid if SecondArgIsLastNamedArgument is false after the next
3361   // block.
3362   QualType Type;
3363   SourceLocation ParamLoc;
3364   bool IsCRegister = false;
3365 
3366   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3367     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3368       // FIXME: This isn't correct for methods (results in bogus warning).
3369       // Get the last formal in the current function.
3370       const ParmVarDecl *LastArg;
3371       if (CurBlock)
3372         LastArg = CurBlock->TheDecl->parameters().back();
3373       else if (FunctionDecl *FD = getCurFunctionDecl())
3374         LastArg = FD->parameters().back();
3375       else
3376         LastArg = getCurMethodDecl()->parameters().back();
3377       SecondArgIsLastNamedArgument = PV == LastArg;
3378 
3379       Type = PV->getType();
3380       ParamLoc = PV->getLocation();
3381       IsCRegister =
3382           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3383     }
3384   }
3385 
3386   if (!SecondArgIsLastNamedArgument)
3387     Diag(TheCall->getArg(1)->getLocStart(),
3388          diag::warn_second_arg_of_va_start_not_last_named_param);
3389   else if (IsCRegister || Type->isReferenceType() ||
3390            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3391              // Promotable integers are UB, but enumerations need a bit of
3392              // extra checking to see what their promotable type actually is.
3393              if (!Type->isPromotableIntegerType())
3394                return false;
3395              if (!Type->isEnumeralType())
3396                return true;
3397              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3398              return !(ED &&
3399                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3400            }()) {
3401     unsigned Reason = 0;
3402     if (Type->isReferenceType())  Reason = 1;
3403     else if (IsCRegister)         Reason = 2;
3404     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3405     Diag(ParamLoc, diag::note_parameter_type) << Type;
3406   }
3407 
3408   TheCall->setType(Context.VoidTy);
3409   return false;
3410 }
3411 
3412 /// Check the arguments to '__builtin_va_start' for validity, and that
3413 /// it was called from a function of the native ABI.
3414 /// Emit an error and return true on failure; return false on success.
3415 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
3416   // On x86-64 Unix, don't allow this in Win64 ABI functions.
3417   // On x64 Windows, don't allow this in System V ABI functions.
3418   // (Yes, that means there's no corresponding way to support variadic
3419   // System V ABI functions on Windows.)
3420   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
3421     unsigned OS = Context.getTargetInfo().getTriple().getOS();
3422     clang::CallingConv CC = CC_C;
3423     if (const FunctionDecl *FD = getCurFunctionDecl())
3424       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3425     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
3426         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
3427       return Diag(TheCall->getCallee()->getLocStart(),
3428                   diag::err_va_start_used_in_wrong_abi_function)
3429              << (OS != llvm::Triple::Win32);
3430   }
3431   return SemaBuiltinVAStartImpl(TheCall);
3432 }
3433 
3434 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
3435 /// it was called from a Win64 ABI function.
3436 /// Emit an error and return true on failure; return false on success.
3437 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
3438   // This only makes sense for x86-64.
3439   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3440   Expr *Callee = TheCall->getCallee();
3441   if (TT.getArch() != llvm::Triple::x86_64)
3442     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
3443   // Don't allow this in System V ABI functions.
3444   clang::CallingConv CC = CC_C;
3445   if (const FunctionDecl *FD = getCurFunctionDecl())
3446     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3447   if (CC == CC_X86_64SysV ||
3448       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
3449     return Diag(Callee->getLocStart(),
3450                 diag::err_ms_va_start_used_in_sysv_function);
3451   return SemaBuiltinVAStartImpl(TheCall);
3452 }
3453 
3454 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3455   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3456   //                 const char *named_addr);
3457 
3458   Expr *Func = Call->getCallee();
3459 
3460   if (Call->getNumArgs() < 3)
3461     return Diag(Call->getLocEnd(),
3462                 diag::err_typecheck_call_too_few_args_at_least)
3463            << 0 /*function call*/ << 3 << Call->getNumArgs();
3464 
3465   // Determine whether the current function is variadic or not.
3466   bool IsVariadic;
3467   if (BlockScopeInfo *CurBlock = getCurBlock())
3468     IsVariadic = CurBlock->TheDecl->isVariadic();
3469   else if (FunctionDecl *FD = getCurFunctionDecl())
3470     IsVariadic = FD->isVariadic();
3471   else if (ObjCMethodDecl *MD = getCurMethodDecl())
3472     IsVariadic = MD->isVariadic();
3473   else
3474     llvm_unreachable("unexpected statement type");
3475 
3476   if (!IsVariadic) {
3477     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
3478     return true;
3479   }
3480 
3481   // Type-check the first argument normally.
3482   if (checkBuiltinArgument(*this, Call, 0))
3483     return true;
3484 
3485   const struct {
3486     unsigned ArgNo;
3487     QualType Type;
3488   } ArgumentTypes[] = {
3489     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3490     { 2, Context.getSizeType() },
3491   };
3492 
3493   for (const auto &AT : ArgumentTypes) {
3494     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3495     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3496       continue;
3497     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3498       << Arg->getType() << AT.Type << 1 /* different class */
3499       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3500       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3501   }
3502 
3503   return false;
3504 }
3505 
3506 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3507 /// friends.  This is declared to take (...), so we have to check everything.
3508 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3509   if (TheCall->getNumArgs() < 2)
3510     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3511       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3512   if (TheCall->getNumArgs() > 2)
3513     return Diag(TheCall->getArg(2)->getLocStart(),
3514                 diag::err_typecheck_call_too_many_args)
3515       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3516       << SourceRange(TheCall->getArg(2)->getLocStart(),
3517                      (*(TheCall->arg_end()-1))->getLocEnd());
3518 
3519   ExprResult OrigArg0 = TheCall->getArg(0);
3520   ExprResult OrigArg1 = TheCall->getArg(1);
3521 
3522   // Do standard promotions between the two arguments, returning their common
3523   // type.
3524   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3525   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3526     return true;
3527 
3528   // Make sure any conversions are pushed back into the call; this is
3529   // type safe since unordered compare builtins are declared as "_Bool
3530   // foo(...)".
3531   TheCall->setArg(0, OrigArg0.get());
3532   TheCall->setArg(1, OrigArg1.get());
3533 
3534   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3535     return false;
3536 
3537   // If the common type isn't a real floating type, then the arguments were
3538   // invalid for this operation.
3539   if (Res.isNull() || !Res->isRealFloatingType())
3540     return Diag(OrigArg0.get()->getLocStart(),
3541                 diag::err_typecheck_call_invalid_ordered_compare)
3542       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
3543       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
3544 
3545   return false;
3546 }
3547 
3548 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
3549 /// __builtin_isnan and friends.  This is declared to take (...), so we have
3550 /// to check everything. We expect the last argument to be a floating point
3551 /// value.
3552 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
3553   if (TheCall->getNumArgs() < NumArgs)
3554     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3555       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
3556   if (TheCall->getNumArgs() > NumArgs)
3557     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
3558                 diag::err_typecheck_call_too_many_args)
3559       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
3560       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
3561                      (*(TheCall->arg_end()-1))->getLocEnd());
3562 
3563   Expr *OrigArg = TheCall->getArg(NumArgs-1);
3564 
3565   if (OrigArg->isTypeDependent())
3566     return false;
3567 
3568   // This operation requires a non-_Complex floating-point number.
3569   if (!OrigArg->getType()->isRealFloatingType())
3570     return Diag(OrigArg->getLocStart(),
3571                 diag::err_typecheck_call_invalid_unary_fp)
3572       << OrigArg->getType() << OrigArg->getSourceRange();
3573 
3574   // If this is an implicit conversion from float -> double, remove it.
3575   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
3576     Expr *CastArg = Cast->getSubExpr();
3577     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
3578       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
3579              "promotion from float to double is the only expected cast here");
3580       Cast->setSubExpr(nullptr);
3581       TheCall->setArg(NumArgs-1, CastArg);
3582     }
3583   }
3584 
3585   return false;
3586 }
3587 
3588 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
3589 // This is declared to take (...), so we have to check everything.
3590 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
3591   if (TheCall->getNumArgs() < 2)
3592     return ExprError(Diag(TheCall->getLocEnd(),
3593                           diag::err_typecheck_call_too_few_args_at_least)
3594                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3595                      << TheCall->getSourceRange());
3596 
3597   // Determine which of the following types of shufflevector we're checking:
3598   // 1) unary, vector mask: (lhs, mask)
3599   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
3600   QualType resType = TheCall->getArg(0)->getType();
3601   unsigned numElements = 0;
3602 
3603   if (!TheCall->getArg(0)->isTypeDependent() &&
3604       !TheCall->getArg(1)->isTypeDependent()) {
3605     QualType LHSType = TheCall->getArg(0)->getType();
3606     QualType RHSType = TheCall->getArg(1)->getType();
3607 
3608     if (!LHSType->isVectorType() || !RHSType->isVectorType())
3609       return ExprError(Diag(TheCall->getLocStart(),
3610                             diag::err_shufflevector_non_vector)
3611                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3612                                       TheCall->getArg(1)->getLocEnd()));
3613 
3614     numElements = LHSType->getAs<VectorType>()->getNumElements();
3615     unsigned numResElements = TheCall->getNumArgs() - 2;
3616 
3617     // Check to see if we have a call with 2 vector arguments, the unary shuffle
3618     // with mask.  If so, verify that RHS is an integer vector type with the
3619     // same number of elts as lhs.
3620     if (TheCall->getNumArgs() == 2) {
3621       if (!RHSType->hasIntegerRepresentation() ||
3622           RHSType->getAs<VectorType>()->getNumElements() != numElements)
3623         return ExprError(Diag(TheCall->getLocStart(),
3624                               diag::err_shufflevector_incompatible_vector)
3625                          << SourceRange(TheCall->getArg(1)->getLocStart(),
3626                                         TheCall->getArg(1)->getLocEnd()));
3627     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
3628       return ExprError(Diag(TheCall->getLocStart(),
3629                             diag::err_shufflevector_incompatible_vector)
3630                        << SourceRange(TheCall->getArg(0)->getLocStart(),
3631                                       TheCall->getArg(1)->getLocEnd()));
3632     } else if (numElements != numResElements) {
3633       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
3634       resType = Context.getVectorType(eltType, numResElements,
3635                                       VectorType::GenericVector);
3636     }
3637   }
3638 
3639   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
3640     if (TheCall->getArg(i)->isTypeDependent() ||
3641         TheCall->getArg(i)->isValueDependent())
3642       continue;
3643 
3644     llvm::APSInt Result(32);
3645     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
3646       return ExprError(Diag(TheCall->getLocStart(),
3647                             diag::err_shufflevector_nonconstant_argument)
3648                        << TheCall->getArg(i)->getSourceRange());
3649 
3650     // Allow -1 which will be translated to undef in the IR.
3651     if (Result.isSigned() && Result.isAllOnesValue())
3652       continue;
3653 
3654     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
3655       return ExprError(Diag(TheCall->getLocStart(),
3656                             diag::err_shufflevector_argument_too_large)
3657                        << TheCall->getArg(i)->getSourceRange());
3658   }
3659 
3660   SmallVector<Expr*, 32> exprs;
3661 
3662   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
3663     exprs.push_back(TheCall->getArg(i));
3664     TheCall->setArg(i, nullptr);
3665   }
3666 
3667   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3668                                          TheCall->getCallee()->getLocStart(),
3669                                          TheCall->getRParenLoc());
3670 }
3671 
3672 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3673 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3674                                        SourceLocation BuiltinLoc,
3675                                        SourceLocation RParenLoc) {
3676   ExprValueKind VK = VK_RValue;
3677   ExprObjectKind OK = OK_Ordinary;
3678   QualType DstTy = TInfo->getType();
3679   QualType SrcTy = E->getType();
3680 
3681   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3682     return ExprError(Diag(BuiltinLoc,
3683                           diag::err_convertvector_non_vector)
3684                      << E->getSourceRange());
3685   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3686     return ExprError(Diag(BuiltinLoc,
3687                           diag::err_convertvector_non_vector_type));
3688 
3689   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3690     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3691     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3692     if (SrcElts != DstElts)
3693       return ExprError(Diag(BuiltinLoc,
3694                             diag::err_convertvector_incompatible_vector)
3695                        << E->getSourceRange());
3696   }
3697 
3698   return new (Context)
3699       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3700 }
3701 
3702 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3703 // This is declared to take (const void*, ...) and can take two
3704 // optional constant int args.
3705 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3706   unsigned NumArgs = TheCall->getNumArgs();
3707 
3708   if (NumArgs > 3)
3709     return Diag(TheCall->getLocEnd(),
3710              diag::err_typecheck_call_too_many_args_at_most)
3711              << 0 /*function call*/ << 3 << NumArgs
3712              << TheCall->getSourceRange();
3713 
3714   // Argument 0 is checked for us and the remaining arguments must be
3715   // constant integers.
3716   for (unsigned i = 1; i != NumArgs; ++i)
3717     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3718       return true;
3719 
3720   return false;
3721 }
3722 
3723 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3724 // __assume does not evaluate its arguments, and should warn if its argument
3725 // has side effects.
3726 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3727   Expr *Arg = TheCall->getArg(0);
3728   if (Arg->isInstantiationDependent()) return false;
3729 
3730   if (Arg->HasSideEffects(Context))
3731     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3732       << Arg->getSourceRange()
3733       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3734 
3735   return false;
3736 }
3737 
3738 /// Handle __builtin_assume_aligned. This is declared
3739 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3740 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3741   unsigned NumArgs = TheCall->getNumArgs();
3742 
3743   if (NumArgs > 3)
3744     return Diag(TheCall->getLocEnd(),
3745              diag::err_typecheck_call_too_many_args_at_most)
3746              << 0 /*function call*/ << 3 << NumArgs
3747              << TheCall->getSourceRange();
3748 
3749   // The alignment must be a constant integer.
3750   Expr *Arg = TheCall->getArg(1);
3751 
3752   // We can't check the value of a dependent argument.
3753   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3754     llvm::APSInt Result;
3755     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3756       return true;
3757 
3758     if (!Result.isPowerOf2())
3759       return Diag(TheCall->getLocStart(),
3760                   diag::err_alignment_not_power_of_two)
3761            << Arg->getSourceRange();
3762   }
3763 
3764   if (NumArgs > 2) {
3765     ExprResult Arg(TheCall->getArg(2));
3766     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3767       Context.getSizeType(), false);
3768     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3769     if (Arg.isInvalid()) return true;
3770     TheCall->setArg(2, Arg.get());
3771   }
3772 
3773   return false;
3774 }
3775 
3776 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3777 /// TheCall is a constant expression.
3778 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3779                                   llvm::APSInt &Result) {
3780   Expr *Arg = TheCall->getArg(ArgNum);
3781   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3782   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3783 
3784   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3785 
3786   if (!Arg->isIntegerConstantExpr(Result, Context))
3787     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3788                 << FDecl->getDeclName() <<  Arg->getSourceRange();
3789 
3790   return false;
3791 }
3792 
3793 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3794 /// TheCall is a constant expression in the range [Low, High].
3795 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3796                                        int Low, int High) {
3797   llvm::APSInt Result;
3798 
3799   // We can't check the value of a dependent argument.
3800   Expr *Arg = TheCall->getArg(ArgNum);
3801   if (Arg->isTypeDependent() || Arg->isValueDependent())
3802     return false;
3803 
3804   // Check constant-ness first.
3805   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3806     return true;
3807 
3808   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3809     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3810       << Low << High << Arg->getSourceRange();
3811 
3812   return false;
3813 }
3814 
3815 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3816 /// TheCall is an ARM/AArch64 special register string literal.
3817 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3818                                     int ArgNum, unsigned ExpectedFieldNum,
3819                                     bool AllowName) {
3820   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3821                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3822                       BuiltinID == ARM::BI__builtin_arm_rsr ||
3823                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3824                       BuiltinID == ARM::BI__builtin_arm_wsr ||
3825                       BuiltinID == ARM::BI__builtin_arm_wsrp;
3826   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3827                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3828                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
3829                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3830                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
3831                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
3832   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3833 
3834   // We can't check the value of a dependent argument.
3835   Expr *Arg = TheCall->getArg(ArgNum);
3836   if (Arg->isTypeDependent() || Arg->isValueDependent())
3837     return false;
3838 
3839   // Check if the argument is a string literal.
3840   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3841     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3842            << Arg->getSourceRange();
3843 
3844   // Check the type of special register given.
3845   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3846   SmallVector<StringRef, 6> Fields;
3847   Reg.split(Fields, ":");
3848 
3849   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3850     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3851            << Arg->getSourceRange();
3852 
3853   // If the string is the name of a register then we cannot check that it is
3854   // valid here but if the string is of one the forms described in ACLE then we
3855   // can check that the supplied fields are integers and within the valid
3856   // ranges.
3857   if (Fields.size() > 1) {
3858     bool FiveFields = Fields.size() == 5;
3859 
3860     bool ValidString = true;
3861     if (IsARMBuiltin) {
3862       ValidString &= Fields[0].startswith_lower("cp") ||
3863                      Fields[0].startswith_lower("p");
3864       if (ValidString)
3865         Fields[0] =
3866           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3867 
3868       ValidString &= Fields[2].startswith_lower("c");
3869       if (ValidString)
3870         Fields[2] = Fields[2].drop_front(1);
3871 
3872       if (FiveFields) {
3873         ValidString &= Fields[3].startswith_lower("c");
3874         if (ValidString)
3875           Fields[3] = Fields[3].drop_front(1);
3876       }
3877     }
3878 
3879     SmallVector<int, 5> Ranges;
3880     if (FiveFields)
3881       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3882     else
3883       Ranges.append({15, 7, 15});
3884 
3885     for (unsigned i=0; i<Fields.size(); ++i) {
3886       int IntField;
3887       ValidString &= !Fields[i].getAsInteger(10, IntField);
3888       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3889     }
3890 
3891     if (!ValidString)
3892       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3893              << Arg->getSourceRange();
3894 
3895   } else if (IsAArch64Builtin && Fields.size() == 1) {
3896     // If the register name is one of those that appear in the condition below
3897     // and the special register builtin being used is one of the write builtins,
3898     // then we require that the argument provided for writing to the register
3899     // is an integer constant expression. This is because it will be lowered to
3900     // an MSR (immediate) instruction, so we need to know the immediate at
3901     // compile time.
3902     if (TheCall->getNumArgs() != 2)
3903       return false;
3904 
3905     std::string RegLower = Reg.lower();
3906     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3907         RegLower != "pan" && RegLower != "uao")
3908       return false;
3909 
3910     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3911   }
3912 
3913   return false;
3914 }
3915 
3916 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3917 /// This checks that the target supports __builtin_longjmp and
3918 /// that val is a constant 1.
3919 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
3920   if (!Context.getTargetInfo().hasSjLjLowering())
3921     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3922              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3923 
3924   Expr *Arg = TheCall->getArg(1);
3925   llvm::APSInt Result;
3926 
3927   // TODO: This is less than ideal. Overload this to take a value.
3928   if (SemaBuiltinConstantArg(TheCall, 1, Result))
3929     return true;
3930 
3931   if (Result != 1)
3932     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3933              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3934 
3935   return false;
3936 }
3937 
3938 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3939 /// This checks that the target supports __builtin_setjmp.
3940 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3941   if (!Context.getTargetInfo().hasSjLjLowering())
3942     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3943              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3944   return false;
3945 }
3946 
3947 namespace {
3948 class UncoveredArgHandler {
3949   enum { Unknown = -1, AllCovered = -2 };
3950   signed FirstUncoveredArg;
3951   SmallVector<const Expr *, 4> DiagnosticExprs;
3952 
3953 public:
3954   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3955 
3956   bool hasUncoveredArg() const {
3957     return (FirstUncoveredArg >= 0);
3958   }
3959 
3960   unsigned getUncoveredArg() const {
3961     assert(hasUncoveredArg() && "no uncovered argument");
3962     return FirstUncoveredArg;
3963   }
3964 
3965   void setAllCovered() {
3966     // A string has been found with all arguments covered, so clear out
3967     // the diagnostics.
3968     DiagnosticExprs.clear();
3969     FirstUncoveredArg = AllCovered;
3970   }
3971 
3972   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3973     assert(NewFirstUncoveredArg >= 0 && "Outside range");
3974 
3975     // Don't update if a previous string covers all arguments.
3976     if (FirstUncoveredArg == AllCovered)
3977       return;
3978 
3979     // UncoveredArgHandler tracks the highest uncovered argument index
3980     // and with it all the strings that match this index.
3981     if (NewFirstUncoveredArg == FirstUncoveredArg)
3982       DiagnosticExprs.push_back(StrExpr);
3983     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3984       DiagnosticExprs.clear();
3985       DiagnosticExprs.push_back(StrExpr);
3986       FirstUncoveredArg = NewFirstUncoveredArg;
3987     }
3988   }
3989 
3990   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3991 };
3992 
3993 enum StringLiteralCheckType {
3994   SLCT_NotALiteral,
3995   SLCT_UncheckedLiteral,
3996   SLCT_CheckedLiteral
3997 };
3998 } // end anonymous namespace
3999 
4000 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4001                                      BinaryOperatorKind BinOpKind,
4002                                      bool AddendIsRight) {
4003   unsigned BitWidth = Offset.getBitWidth();
4004   unsigned AddendBitWidth = Addend.getBitWidth();
4005   // There might be negative interim results.
4006   if (Addend.isUnsigned()) {
4007     Addend = Addend.zext(++AddendBitWidth);
4008     Addend.setIsSigned(true);
4009   }
4010   // Adjust the bit width of the APSInts.
4011   if (AddendBitWidth > BitWidth) {
4012     Offset = Offset.sext(AddendBitWidth);
4013     BitWidth = AddendBitWidth;
4014   } else if (BitWidth > AddendBitWidth) {
4015     Addend = Addend.sext(BitWidth);
4016   }
4017 
4018   bool Ov = false;
4019   llvm::APSInt ResOffset = Offset;
4020   if (BinOpKind == BO_Add)
4021     ResOffset = Offset.sadd_ov(Addend, Ov);
4022   else {
4023     assert(AddendIsRight && BinOpKind == BO_Sub &&
4024            "operator must be add or sub with addend on the right");
4025     ResOffset = Offset.ssub_ov(Addend, Ov);
4026   }
4027 
4028   // We add an offset to a pointer here so we should support an offset as big as
4029   // possible.
4030   if (Ov) {
4031     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4032     Offset = Offset.sext(2 * BitWidth);
4033     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4034     return;
4035   }
4036 
4037   Offset = ResOffset;
4038 }
4039 
4040 namespace {
4041 // This is a wrapper class around StringLiteral to support offsetted string
4042 // literals as format strings. It takes the offset into account when returning
4043 // the string and its length or the source locations to display notes correctly.
4044 class FormatStringLiteral {
4045   const StringLiteral *FExpr;
4046   int64_t Offset;
4047 
4048  public:
4049   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4050       : FExpr(fexpr), Offset(Offset) {}
4051 
4052   StringRef getString() const {
4053     return FExpr->getString().drop_front(Offset);
4054   }
4055 
4056   unsigned getByteLength() const {
4057     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4058   }
4059   unsigned getLength() const { return FExpr->getLength() - Offset; }
4060   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4061 
4062   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4063 
4064   QualType getType() const { return FExpr->getType(); }
4065 
4066   bool isAscii() const { return FExpr->isAscii(); }
4067   bool isWide() const { return FExpr->isWide(); }
4068   bool isUTF8() const { return FExpr->isUTF8(); }
4069   bool isUTF16() const { return FExpr->isUTF16(); }
4070   bool isUTF32() const { return FExpr->isUTF32(); }
4071   bool isPascal() const { return FExpr->isPascal(); }
4072 
4073   SourceLocation getLocationOfByte(
4074       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4075       const TargetInfo &Target, unsigned *StartToken = nullptr,
4076       unsigned *StartTokenByteOffset = nullptr) const {
4077     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4078                                     StartToken, StartTokenByteOffset);
4079   }
4080 
4081   SourceLocation getLocStart() const LLVM_READONLY {
4082     return FExpr->getLocStart().getLocWithOffset(Offset);
4083   }
4084   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4085 };
4086 }  // end anonymous namespace
4087 
4088 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4089                               const Expr *OrigFormatExpr,
4090                               ArrayRef<const Expr *> Args,
4091                               bool HasVAListArg, unsigned format_idx,
4092                               unsigned firstDataArg,
4093                               Sema::FormatStringType Type,
4094                               bool inFunctionCall,
4095                               Sema::VariadicCallType CallType,
4096                               llvm::SmallBitVector &CheckedVarArgs,
4097                               UncoveredArgHandler &UncoveredArg);
4098 
4099 // Determine if an expression is a string literal or constant string.
4100 // If this function returns false on the arguments to a function expecting a
4101 // format string, we will usually need to emit a warning.
4102 // True string literals are then checked by CheckFormatString.
4103 static StringLiteralCheckType
4104 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4105                       bool HasVAListArg, unsigned format_idx,
4106                       unsigned firstDataArg, Sema::FormatStringType Type,
4107                       Sema::VariadicCallType CallType, bool InFunctionCall,
4108                       llvm::SmallBitVector &CheckedVarArgs,
4109                       UncoveredArgHandler &UncoveredArg,
4110                       llvm::APSInt Offset) {
4111  tryAgain:
4112   assert(Offset.isSigned() && "invalid offset");
4113 
4114   if (E->isTypeDependent() || E->isValueDependent())
4115     return SLCT_NotALiteral;
4116 
4117   E = E->IgnoreParenCasts();
4118 
4119   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4120     // Technically -Wformat-nonliteral does not warn about this case.
4121     // The behavior of printf and friends in this case is implementation
4122     // dependent.  Ideally if the format string cannot be null then
4123     // it should have a 'nonnull' attribute in the function prototype.
4124     return SLCT_UncheckedLiteral;
4125 
4126   switch (E->getStmtClass()) {
4127   case Stmt::BinaryConditionalOperatorClass:
4128   case Stmt::ConditionalOperatorClass: {
4129     // The expression is a literal if both sub-expressions were, and it was
4130     // completely checked only if both sub-expressions were checked.
4131     const AbstractConditionalOperator *C =
4132         cast<AbstractConditionalOperator>(E);
4133 
4134     // Determine whether it is necessary to check both sub-expressions, for
4135     // example, because the condition expression is a constant that can be
4136     // evaluated at compile time.
4137     bool CheckLeft = true, CheckRight = true;
4138 
4139     bool Cond;
4140     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4141       if (Cond)
4142         CheckRight = false;
4143       else
4144         CheckLeft = false;
4145     }
4146 
4147     // We need to maintain the offsets for the right and the left hand side
4148     // separately to check if every possible indexed expression is a valid
4149     // string literal. They might have different offsets for different string
4150     // literals in the end.
4151     StringLiteralCheckType Left;
4152     if (!CheckLeft)
4153       Left = SLCT_UncheckedLiteral;
4154     else {
4155       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4156                                    HasVAListArg, format_idx, firstDataArg,
4157                                    Type, CallType, InFunctionCall,
4158                                    CheckedVarArgs, UncoveredArg, Offset);
4159       if (Left == SLCT_NotALiteral || !CheckRight) {
4160         return Left;
4161       }
4162     }
4163 
4164     StringLiteralCheckType Right =
4165         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4166                               HasVAListArg, format_idx, firstDataArg,
4167                               Type, CallType, InFunctionCall, CheckedVarArgs,
4168                               UncoveredArg, Offset);
4169 
4170     return (CheckLeft && Left < Right) ? Left : Right;
4171   }
4172 
4173   case Stmt::ImplicitCastExprClass: {
4174     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4175     goto tryAgain;
4176   }
4177 
4178   case Stmt::OpaqueValueExprClass:
4179     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4180       E = src;
4181       goto tryAgain;
4182     }
4183     return SLCT_NotALiteral;
4184 
4185   case Stmt::PredefinedExprClass:
4186     // While __func__, etc., are technically not string literals, they
4187     // cannot contain format specifiers and thus are not a security
4188     // liability.
4189     return SLCT_UncheckedLiteral;
4190 
4191   case Stmt::DeclRefExprClass: {
4192     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4193 
4194     // As an exception, do not flag errors for variables binding to
4195     // const string literals.
4196     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4197       bool isConstant = false;
4198       QualType T = DR->getType();
4199 
4200       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4201         isConstant = AT->getElementType().isConstant(S.Context);
4202       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4203         isConstant = T.isConstant(S.Context) &&
4204                      PT->getPointeeType().isConstant(S.Context);
4205       } else if (T->isObjCObjectPointerType()) {
4206         // In ObjC, there is usually no "const ObjectPointer" type,
4207         // so don't check if the pointee type is constant.
4208         isConstant = T.isConstant(S.Context);
4209       }
4210 
4211       if (isConstant) {
4212         if (const Expr *Init = VD->getAnyInitializer()) {
4213           // Look through initializers like const char c[] = { "foo" }
4214           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4215             if (InitList->isStringLiteralInit())
4216               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4217           }
4218           return checkFormatStringExpr(S, Init, Args,
4219                                        HasVAListArg, format_idx,
4220                                        firstDataArg, Type, CallType,
4221                                        /*InFunctionCall*/ false, CheckedVarArgs,
4222                                        UncoveredArg, Offset);
4223         }
4224       }
4225 
4226       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4227       // special check to see if the format string is a function parameter
4228       // of the function calling the printf function.  If the function
4229       // has an attribute indicating it is a printf-like function, then we
4230       // should suppress warnings concerning non-literals being used in a call
4231       // to a vprintf function.  For example:
4232       //
4233       // void
4234       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4235       //      va_list ap;
4236       //      va_start(ap, fmt);
4237       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4238       //      ...
4239       // }
4240       if (HasVAListArg) {
4241         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4242           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4243             int PVIndex = PV->getFunctionScopeIndex() + 1;
4244             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4245               // adjust for implicit parameter
4246               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4247                 if (MD->isInstance())
4248                   ++PVIndex;
4249               // We also check if the formats are compatible.
4250               // We can't pass a 'scanf' string to a 'printf' function.
4251               if (PVIndex == PVFormat->getFormatIdx() &&
4252                   Type == S.GetFormatStringType(PVFormat))
4253                 return SLCT_UncheckedLiteral;
4254             }
4255           }
4256         }
4257       }
4258     }
4259 
4260     return SLCT_NotALiteral;
4261   }
4262 
4263   case Stmt::CallExprClass:
4264   case Stmt::CXXMemberCallExprClass: {
4265     const CallExpr *CE = cast<CallExpr>(E);
4266     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4267       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4268         unsigned ArgIndex = FA->getFormatIdx();
4269         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4270           if (MD->isInstance())
4271             --ArgIndex;
4272         const Expr *Arg = CE->getArg(ArgIndex - 1);
4273 
4274         return checkFormatStringExpr(S, Arg, Args,
4275                                      HasVAListArg, format_idx, firstDataArg,
4276                                      Type, CallType, InFunctionCall,
4277                                      CheckedVarArgs, UncoveredArg, Offset);
4278       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4279         unsigned BuiltinID = FD->getBuiltinID();
4280         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4281             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4282           const Expr *Arg = CE->getArg(0);
4283           return checkFormatStringExpr(S, Arg, Args,
4284                                        HasVAListArg, format_idx,
4285                                        firstDataArg, Type, CallType,
4286                                        InFunctionCall, CheckedVarArgs,
4287                                        UncoveredArg, Offset);
4288         }
4289       }
4290     }
4291 
4292     return SLCT_NotALiteral;
4293   }
4294   case Stmt::ObjCStringLiteralClass:
4295   case Stmt::StringLiteralClass: {
4296     const StringLiteral *StrE = nullptr;
4297 
4298     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4299       StrE = ObjCFExpr->getString();
4300     else
4301       StrE = cast<StringLiteral>(E);
4302 
4303     if (StrE) {
4304       if (Offset.isNegative() || Offset > StrE->getLength()) {
4305         // TODO: It would be better to have an explicit warning for out of
4306         // bounds literals.
4307         return SLCT_NotALiteral;
4308       }
4309       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4310       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4311                         firstDataArg, Type, InFunctionCall, CallType,
4312                         CheckedVarArgs, UncoveredArg);
4313       return SLCT_CheckedLiteral;
4314     }
4315 
4316     return SLCT_NotALiteral;
4317   }
4318   case Stmt::BinaryOperatorClass: {
4319     llvm::APSInt LResult;
4320     llvm::APSInt RResult;
4321 
4322     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
4323 
4324     // A string literal + an int offset is still a string literal.
4325     if (BinOp->isAdditiveOp()) {
4326       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
4327       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
4328 
4329       if (LIsInt != RIsInt) {
4330         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
4331 
4332         if (LIsInt) {
4333           if (BinOpKind == BO_Add) {
4334             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4335             E = BinOp->getRHS();
4336             goto tryAgain;
4337           }
4338         } else {
4339           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4340           E = BinOp->getLHS();
4341           goto tryAgain;
4342         }
4343       }
4344     }
4345 
4346     return SLCT_NotALiteral;
4347   }
4348   case Stmt::UnaryOperatorClass: {
4349     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
4350     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
4351     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
4352       llvm::APSInt IndexResult;
4353       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
4354         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
4355         E = ASE->getBase();
4356         goto tryAgain;
4357       }
4358     }
4359 
4360     return SLCT_NotALiteral;
4361   }
4362 
4363   default:
4364     return SLCT_NotALiteral;
4365   }
4366 }
4367 
4368 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
4369   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4370   .Case("scanf", FST_Scanf)
4371   .Cases("printf", "printf0", FST_Printf)
4372   .Cases("NSString", "CFString", FST_NSString)
4373   .Case("strftime", FST_Strftime)
4374   .Case("strfmon", FST_Strfmon)
4375   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
4376   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
4377   .Case("os_trace", FST_OSTrace)
4378   .Default(FST_Unknown);
4379 }
4380 
4381 /// CheckFormatArguments - Check calls to printf and scanf (and similar
4382 /// functions) for correct use of format strings.
4383 /// Returns true if a format string has been fully checked.
4384 bool Sema::CheckFormatArguments(const FormatAttr *Format,
4385                                 ArrayRef<const Expr *> Args,
4386                                 bool IsCXXMember,
4387                                 VariadicCallType CallType,
4388                                 SourceLocation Loc, SourceRange Range,
4389                                 llvm::SmallBitVector &CheckedVarArgs) {
4390   FormatStringInfo FSI;
4391   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4392     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4393                                 FSI.FirstDataArg, GetFormatStringType(Format),
4394                                 CallType, Loc, Range, CheckedVarArgs);
4395   return false;
4396 }
4397 
4398 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4399                                 bool HasVAListArg, unsigned format_idx,
4400                                 unsigned firstDataArg, FormatStringType Type,
4401                                 VariadicCallType CallType,
4402                                 SourceLocation Loc, SourceRange Range,
4403                                 llvm::SmallBitVector &CheckedVarArgs) {
4404   // CHECK: printf/scanf-like function is called with no format string.
4405   if (format_idx >= Args.size()) {
4406     Diag(Loc, diag::warn_missing_format_string) << Range;
4407     return false;
4408   }
4409 
4410   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
4411 
4412   // CHECK: format string is not a string literal.
4413   //
4414   // Dynamically generated format strings are difficult to
4415   // automatically vet at compile time.  Requiring that format strings
4416   // are string literals: (1) permits the checking of format strings by
4417   // the compiler and thereby (2) can practically remove the source of
4418   // many format string exploits.
4419 
4420   // Format string can be either ObjC string (e.g. @"%d") or
4421   // C string (e.g. "%d")
4422   // ObjC string uses the same format specifiers as C string, so we can use
4423   // the same format string checking logic for both ObjC and C strings.
4424   UncoveredArgHandler UncoveredArg;
4425   StringLiteralCheckType CT =
4426       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
4427                             format_idx, firstDataArg, Type, CallType,
4428                             /*IsFunctionCall*/ true, CheckedVarArgs,
4429                             UncoveredArg,
4430                             /*no string offset*/ llvm::APSInt(64, false) = 0);
4431 
4432   // Generate a diagnostic where an uncovered argument is detected.
4433   if (UncoveredArg.hasUncoveredArg()) {
4434     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4435     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
4436     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
4437   }
4438 
4439   if (CT != SLCT_NotALiteral)
4440     // Literal format string found, check done!
4441     return CT == SLCT_CheckedLiteral;
4442 
4443   // Strftime is particular as it always uses a single 'time' argument,
4444   // so it is safe to pass a non-literal string.
4445   if (Type == FST_Strftime)
4446     return false;
4447 
4448   // Do not emit diag when the string param is a macro expansion and the
4449   // format is either NSString or CFString. This is a hack to prevent
4450   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
4451   // which are usually used in place of NS and CF string literals.
4452   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
4453   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
4454     return false;
4455 
4456   // If there are no arguments specified, warn with -Wformat-security, otherwise
4457   // warn only with -Wformat-nonliteral.
4458   if (Args.size() == firstDataArg) {
4459     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4460       << OrigFormatExpr->getSourceRange();
4461     switch (Type) {
4462     default:
4463       break;
4464     case FST_Kprintf:
4465     case FST_FreeBSDKPrintf:
4466     case FST_Printf:
4467       Diag(FormatLoc, diag::note_format_security_fixit)
4468         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
4469       break;
4470     case FST_NSString:
4471       Diag(FormatLoc, diag::note_format_security_fixit)
4472         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
4473       break;
4474     }
4475   } else {
4476     Diag(FormatLoc, diag::warn_format_nonliteral)
4477       << OrigFormatExpr->getSourceRange();
4478   }
4479   return false;
4480 }
4481 
4482 namespace {
4483 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
4484 protected:
4485   Sema &S;
4486   const FormatStringLiteral *FExpr;
4487   const Expr *OrigFormatExpr;
4488   const unsigned FirstDataArg;
4489   const unsigned NumDataArgs;
4490   const char *Beg; // Start of format string.
4491   const bool HasVAListArg;
4492   ArrayRef<const Expr *> Args;
4493   unsigned FormatIdx;
4494   llvm::SmallBitVector CoveredArgs;
4495   bool usesPositionalArgs;
4496   bool atFirstArg;
4497   bool inFunctionCall;
4498   Sema::VariadicCallType CallType;
4499   llvm::SmallBitVector &CheckedVarArgs;
4500   UncoveredArgHandler &UncoveredArg;
4501 
4502 public:
4503   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
4504                      const Expr *origFormatExpr, unsigned firstDataArg,
4505                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
4506                      ArrayRef<const Expr *> Args,
4507                      unsigned formatIdx, bool inFunctionCall,
4508                      Sema::VariadicCallType callType,
4509                      llvm::SmallBitVector &CheckedVarArgs,
4510                      UncoveredArgHandler &UncoveredArg)
4511     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
4512       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
4513       Beg(beg), HasVAListArg(hasVAListArg),
4514       Args(Args), FormatIdx(formatIdx),
4515       usesPositionalArgs(false), atFirstArg(true),
4516       inFunctionCall(inFunctionCall), CallType(callType),
4517       CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
4518     CoveredArgs.resize(numDataArgs);
4519     CoveredArgs.reset();
4520   }
4521 
4522   void DoneProcessing();
4523 
4524   void HandleIncompleteSpecifier(const char *startSpecifier,
4525                                  unsigned specifierLen) override;
4526 
4527   void HandleInvalidLengthModifier(
4528                            const analyze_format_string::FormatSpecifier &FS,
4529                            const analyze_format_string::ConversionSpecifier &CS,
4530                            const char *startSpecifier, unsigned specifierLen,
4531                            unsigned DiagID);
4532 
4533   void HandleNonStandardLengthModifier(
4534                     const analyze_format_string::FormatSpecifier &FS,
4535                     const char *startSpecifier, unsigned specifierLen);
4536 
4537   void HandleNonStandardConversionSpecifier(
4538                     const analyze_format_string::ConversionSpecifier &CS,
4539                     const char *startSpecifier, unsigned specifierLen);
4540 
4541   void HandlePosition(const char *startPos, unsigned posLen) override;
4542 
4543   void HandleInvalidPosition(const char *startSpecifier,
4544                              unsigned specifierLen,
4545                              analyze_format_string::PositionContext p) override;
4546 
4547   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
4548 
4549   void HandleNullChar(const char *nullCharacter) override;
4550 
4551   template <typename Range>
4552   static void
4553   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
4554                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
4555                        bool IsStringLocation, Range StringRange,
4556                        ArrayRef<FixItHint> Fixit = None);
4557 
4558 protected:
4559   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
4560                                         const char *startSpec,
4561                                         unsigned specifierLen,
4562                                         const char *csStart, unsigned csLen);
4563 
4564   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
4565                                          const char *startSpec,
4566                                          unsigned specifierLen);
4567 
4568   SourceRange getFormatStringRange();
4569   CharSourceRange getSpecifierRange(const char *startSpecifier,
4570                                     unsigned specifierLen);
4571   SourceLocation getLocationOfByte(const char *x);
4572 
4573   const Expr *getDataArg(unsigned i) const;
4574 
4575   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
4576                     const analyze_format_string::ConversionSpecifier &CS,
4577                     const char *startSpecifier, unsigned specifierLen,
4578                     unsigned argIndex);
4579 
4580   template <typename Range>
4581   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4582                             bool IsStringLocation, Range StringRange,
4583                             ArrayRef<FixItHint> Fixit = None);
4584 };
4585 } // end anonymous namespace
4586 
4587 SourceRange CheckFormatHandler::getFormatStringRange() {
4588   return OrigFormatExpr->getSourceRange();
4589 }
4590 
4591 CharSourceRange CheckFormatHandler::
4592 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
4593   SourceLocation Start = getLocationOfByte(startSpecifier);
4594   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
4595 
4596   // Advance the end SourceLocation by one due to half-open ranges.
4597   End = End.getLocWithOffset(1);
4598 
4599   return CharSourceRange::getCharRange(Start, End);
4600 }
4601 
4602 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
4603   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
4604                                   S.getLangOpts(), S.Context.getTargetInfo());
4605 }
4606 
4607 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
4608                                                    unsigned specifierLen){
4609   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
4610                        getLocationOfByte(startSpecifier),
4611                        /*IsStringLocation*/true,
4612                        getSpecifierRange(startSpecifier, specifierLen));
4613 }
4614 
4615 void CheckFormatHandler::HandleInvalidLengthModifier(
4616     const analyze_format_string::FormatSpecifier &FS,
4617     const analyze_format_string::ConversionSpecifier &CS,
4618     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
4619   using namespace analyze_format_string;
4620 
4621   const LengthModifier &LM = FS.getLengthModifier();
4622   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4623 
4624   // See if we know how to fix this length modifier.
4625   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4626   if (FixedLM) {
4627     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4628                          getLocationOfByte(LM.getStart()),
4629                          /*IsStringLocation*/true,
4630                          getSpecifierRange(startSpecifier, specifierLen));
4631 
4632     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4633       << FixedLM->toString()
4634       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4635 
4636   } else {
4637     FixItHint Hint;
4638     if (DiagID == diag::warn_format_nonsensical_length)
4639       Hint = FixItHint::CreateRemoval(LMRange);
4640 
4641     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
4642                          getLocationOfByte(LM.getStart()),
4643                          /*IsStringLocation*/true,
4644                          getSpecifierRange(startSpecifier, specifierLen),
4645                          Hint);
4646   }
4647 }
4648 
4649 void CheckFormatHandler::HandleNonStandardLengthModifier(
4650     const analyze_format_string::FormatSpecifier &FS,
4651     const char *startSpecifier, unsigned specifierLen) {
4652   using namespace analyze_format_string;
4653 
4654   const LengthModifier &LM = FS.getLengthModifier();
4655   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
4656 
4657   // See if we know how to fix this length modifier.
4658   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
4659   if (FixedLM) {
4660     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4661                            << LM.toString() << 0,
4662                          getLocationOfByte(LM.getStart()),
4663                          /*IsStringLocation*/true,
4664                          getSpecifierRange(startSpecifier, specifierLen));
4665 
4666     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
4667       << FixedLM->toString()
4668       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
4669 
4670   } else {
4671     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4672                            << LM.toString() << 0,
4673                          getLocationOfByte(LM.getStart()),
4674                          /*IsStringLocation*/true,
4675                          getSpecifierRange(startSpecifier, specifierLen));
4676   }
4677 }
4678 
4679 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
4680     const analyze_format_string::ConversionSpecifier &CS,
4681     const char *startSpecifier, unsigned specifierLen) {
4682   using namespace analyze_format_string;
4683 
4684   // See if we know how to fix this conversion specifier.
4685   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
4686   if (FixedCS) {
4687     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4688                           << CS.toString() << /*conversion specifier*/1,
4689                          getLocationOfByte(CS.getStart()),
4690                          /*IsStringLocation*/true,
4691                          getSpecifierRange(startSpecifier, specifierLen));
4692 
4693     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
4694     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
4695       << FixedCS->toString()
4696       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
4697   } else {
4698     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
4699                           << CS.toString() << /*conversion specifier*/1,
4700                          getLocationOfByte(CS.getStart()),
4701                          /*IsStringLocation*/true,
4702                          getSpecifierRange(startSpecifier, specifierLen));
4703   }
4704 }
4705 
4706 void CheckFormatHandler::HandlePosition(const char *startPos,
4707                                         unsigned posLen) {
4708   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
4709                                getLocationOfByte(startPos),
4710                                /*IsStringLocation*/true,
4711                                getSpecifierRange(startPos, posLen));
4712 }
4713 
4714 void
4715 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
4716                                      analyze_format_string::PositionContext p) {
4717   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
4718                          << (unsigned) p,
4719                        getLocationOfByte(startPos), /*IsStringLocation*/true,
4720                        getSpecifierRange(startPos, posLen));
4721 }
4722 
4723 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
4724                                             unsigned posLen) {
4725   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
4726                                getLocationOfByte(startPos),
4727                                /*IsStringLocation*/true,
4728                                getSpecifierRange(startPos, posLen));
4729 }
4730 
4731 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
4732   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
4733     // The presence of a null character is likely an error.
4734     EmitFormatDiagnostic(
4735       S.PDiag(diag::warn_printf_format_string_contains_null_char),
4736       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
4737       getFormatStringRange());
4738   }
4739 }
4740 
4741 // Note that this may return NULL if there was an error parsing or building
4742 // one of the argument expressions.
4743 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
4744   return Args[FirstDataArg + i];
4745 }
4746 
4747 void CheckFormatHandler::DoneProcessing() {
4748   // Does the number of data arguments exceed the number of
4749   // format conversions in the format string?
4750   if (!HasVAListArg) {
4751       // Find any arguments that weren't covered.
4752     CoveredArgs.flip();
4753     signed notCoveredArg = CoveredArgs.find_first();
4754     if (notCoveredArg >= 0) {
4755       assert((unsigned)notCoveredArg < NumDataArgs);
4756       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
4757     } else {
4758       UncoveredArg.setAllCovered();
4759     }
4760   }
4761 }
4762 
4763 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
4764                                    const Expr *ArgExpr) {
4765   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
4766          "Invalid state");
4767 
4768   if (!ArgExpr)
4769     return;
4770 
4771   SourceLocation Loc = ArgExpr->getLocStart();
4772 
4773   if (S.getSourceManager().isInSystemMacro(Loc))
4774     return;
4775 
4776   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
4777   for (auto E : DiagnosticExprs)
4778     PDiag << E->getSourceRange();
4779 
4780   CheckFormatHandler::EmitFormatDiagnostic(
4781                                   S, IsFunctionCall, DiagnosticExprs[0],
4782                                   PDiag, Loc, /*IsStringLocation*/false,
4783                                   DiagnosticExprs[0]->getSourceRange());
4784 }
4785 
4786 bool
4787 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
4788                                                      SourceLocation Loc,
4789                                                      const char *startSpec,
4790                                                      unsigned specifierLen,
4791                                                      const char *csStart,
4792                                                      unsigned csLen) {
4793   bool keepGoing = true;
4794   if (argIndex < NumDataArgs) {
4795     // Consider the argument coverered, even though the specifier doesn't
4796     // make sense.
4797     CoveredArgs.set(argIndex);
4798   }
4799   else {
4800     // If argIndex exceeds the number of data arguments we
4801     // don't issue a warning because that is just a cascade of warnings (and
4802     // they may have intended '%%' anyway). We don't want to continue processing
4803     // the format string after this point, however, as we will like just get
4804     // gibberish when trying to match arguments.
4805     keepGoing = false;
4806   }
4807 
4808   StringRef Specifier(csStart, csLen);
4809 
4810   // If the specifier in non-printable, it could be the first byte of a UTF-8
4811   // sequence. In that case, print the UTF-8 code point. If not, print the byte
4812   // hex value.
4813   std::string CodePointStr;
4814   if (!llvm::sys::locale::isPrint(*csStart)) {
4815     llvm::UTF32 CodePoint;
4816     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
4817     const llvm::UTF8 *E =
4818         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
4819     llvm::ConversionResult Result =
4820         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
4821 
4822     if (Result != llvm::conversionOK) {
4823       unsigned char FirstChar = *csStart;
4824       CodePoint = (llvm::UTF32)FirstChar;
4825     }
4826 
4827     llvm::raw_string_ostream OS(CodePointStr);
4828     if (CodePoint < 256)
4829       OS << "\\x" << llvm::format("%02x", CodePoint);
4830     else if (CodePoint <= 0xFFFF)
4831       OS << "\\u" << llvm::format("%04x", CodePoint);
4832     else
4833       OS << "\\U" << llvm::format("%08x", CodePoint);
4834     OS.flush();
4835     Specifier = CodePointStr;
4836   }
4837 
4838   EmitFormatDiagnostic(
4839       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4840       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4841 
4842   return keepGoing;
4843 }
4844 
4845 void
4846 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4847                                                       const char *startSpec,
4848                                                       unsigned specifierLen) {
4849   EmitFormatDiagnostic(
4850     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4851     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4852 }
4853 
4854 bool
4855 CheckFormatHandler::CheckNumArgs(
4856   const analyze_format_string::FormatSpecifier &FS,
4857   const analyze_format_string::ConversionSpecifier &CS,
4858   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4859 
4860   if (argIndex >= NumDataArgs) {
4861     PartialDiagnostic PDiag = FS.usesPositionalArg()
4862       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4863            << (argIndex+1) << NumDataArgs)
4864       : S.PDiag(diag::warn_printf_insufficient_data_args);
4865     EmitFormatDiagnostic(
4866       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4867       getSpecifierRange(startSpecifier, specifierLen));
4868 
4869     // Since more arguments than conversion tokens are given, by extension
4870     // all arguments are covered, so mark this as so.
4871     UncoveredArg.setAllCovered();
4872     return false;
4873   }
4874   return true;
4875 }
4876 
4877 template<typename Range>
4878 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4879                                               SourceLocation Loc,
4880                                               bool IsStringLocation,
4881                                               Range StringRange,
4882                                               ArrayRef<FixItHint> FixIt) {
4883   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4884                        Loc, IsStringLocation, StringRange, FixIt);
4885 }
4886 
4887 /// \brief If the format string is not within the funcion call, emit a note
4888 /// so that the function call and string are in diagnostic messages.
4889 ///
4890 /// \param InFunctionCall if true, the format string is within the function
4891 /// call and only one diagnostic message will be produced.  Otherwise, an
4892 /// extra note will be emitted pointing to location of the format string.
4893 ///
4894 /// \param ArgumentExpr the expression that is passed as the format string
4895 /// argument in the function call.  Used for getting locations when two
4896 /// diagnostics are emitted.
4897 ///
4898 /// \param PDiag the callee should already have provided any strings for the
4899 /// diagnostic message.  This function only adds locations and fixits
4900 /// to diagnostics.
4901 ///
4902 /// \param Loc primary location for diagnostic.  If two diagnostics are
4903 /// required, one will be at Loc and a new SourceLocation will be created for
4904 /// the other one.
4905 ///
4906 /// \param IsStringLocation if true, Loc points to the format string should be
4907 /// used for the note.  Otherwise, Loc points to the argument list and will
4908 /// be used with PDiag.
4909 ///
4910 /// \param StringRange some or all of the string to highlight.  This is
4911 /// templated so it can accept either a CharSourceRange or a SourceRange.
4912 ///
4913 /// \param FixIt optional fix it hint for the format string.
4914 template <typename Range>
4915 void CheckFormatHandler::EmitFormatDiagnostic(
4916     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
4917     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
4918     Range StringRange, ArrayRef<FixItHint> FixIt) {
4919   if (InFunctionCall) {
4920     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4921     D << StringRange;
4922     D << FixIt;
4923   } else {
4924     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4925       << ArgumentExpr->getSourceRange();
4926 
4927     const Sema::SemaDiagnosticBuilder &Note =
4928       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4929              diag::note_format_string_defined);
4930 
4931     Note << StringRange;
4932     Note << FixIt;
4933   }
4934 }
4935 
4936 //===--- CHECK: Printf format string checking ------------------------------===//
4937 
4938 namespace {
4939 class CheckPrintfHandler : public CheckFormatHandler {
4940   bool ObjCContext;
4941 
4942 public:
4943   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
4944                      const Expr *origFormatExpr, unsigned firstDataArg,
4945                      unsigned numDataArgs, bool isObjC,
4946                      const char *beg, bool hasVAListArg,
4947                      ArrayRef<const Expr *> Args,
4948                      unsigned formatIdx, bool inFunctionCall,
4949                      Sema::VariadicCallType CallType,
4950                      llvm::SmallBitVector &CheckedVarArgs,
4951                      UncoveredArgHandler &UncoveredArg)
4952     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4953                          numDataArgs, beg, hasVAListArg, Args,
4954                          formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4955                          UncoveredArg),
4956       ObjCContext(isObjC)
4957   {}
4958 
4959   bool HandleInvalidPrintfConversionSpecifier(
4960                                       const analyze_printf::PrintfSpecifier &FS,
4961                                       const char *startSpecifier,
4962                                       unsigned specifierLen) override;
4963 
4964   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4965                              const char *startSpecifier,
4966                              unsigned specifierLen) override;
4967   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4968                        const char *StartSpecifier,
4969                        unsigned SpecifierLen,
4970                        const Expr *E);
4971 
4972   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4973                     const char *startSpecifier, unsigned specifierLen);
4974   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4975                            const analyze_printf::OptionalAmount &Amt,
4976                            unsigned type,
4977                            const char *startSpecifier, unsigned specifierLen);
4978   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4979                   const analyze_printf::OptionalFlag &flag,
4980                   const char *startSpecifier, unsigned specifierLen);
4981   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4982                          const analyze_printf::OptionalFlag &ignoredFlag,
4983                          const analyze_printf::OptionalFlag &flag,
4984                          const char *startSpecifier, unsigned specifierLen);
4985   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
4986                            const Expr *E);
4987 
4988   void HandleEmptyObjCModifierFlag(const char *startFlag,
4989                                    unsigned flagLen) override;
4990 
4991   void HandleInvalidObjCModifierFlag(const char *startFlag,
4992                                             unsigned flagLen) override;
4993 
4994   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4995                                            const char *flagsEnd,
4996                                            const char *conversionPosition)
4997                                              override;
4998 };
4999 } // end anonymous namespace
5000 
5001 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5002                                       const analyze_printf::PrintfSpecifier &FS,
5003                                       const char *startSpecifier,
5004                                       unsigned specifierLen) {
5005   const analyze_printf::PrintfConversionSpecifier &CS =
5006     FS.getConversionSpecifier();
5007 
5008   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5009                                           getLocationOfByte(CS.getStart()),
5010                                           startSpecifier, specifierLen,
5011                                           CS.getStart(), CS.getLength());
5012 }
5013 
5014 bool CheckPrintfHandler::HandleAmount(
5015                                const analyze_format_string::OptionalAmount &Amt,
5016                                unsigned k, const char *startSpecifier,
5017                                unsigned specifierLen) {
5018   if (Amt.hasDataArgument()) {
5019     if (!HasVAListArg) {
5020       unsigned argIndex = Amt.getArgIndex();
5021       if (argIndex >= NumDataArgs) {
5022         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5023                                << k,
5024                              getLocationOfByte(Amt.getStart()),
5025                              /*IsStringLocation*/true,
5026                              getSpecifierRange(startSpecifier, specifierLen));
5027         // Don't do any more checking.  We will just emit
5028         // spurious errors.
5029         return false;
5030       }
5031 
5032       // Type check the data argument.  It should be an 'int'.
5033       // Although not in conformance with C99, we also allow the argument to be
5034       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5035       // doesn't emit a warning for that case.
5036       CoveredArgs.set(argIndex);
5037       const Expr *Arg = getDataArg(argIndex);
5038       if (!Arg)
5039         return false;
5040 
5041       QualType T = Arg->getType();
5042 
5043       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5044       assert(AT.isValid());
5045 
5046       if (!AT.matchesType(S.Context, T)) {
5047         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5048                                << k << AT.getRepresentativeTypeName(S.Context)
5049                                << T << Arg->getSourceRange(),
5050                              getLocationOfByte(Amt.getStart()),
5051                              /*IsStringLocation*/true,
5052                              getSpecifierRange(startSpecifier, specifierLen));
5053         // Don't do any more checking.  We will just emit
5054         // spurious errors.
5055         return false;
5056       }
5057     }
5058   }
5059   return true;
5060 }
5061 
5062 void CheckPrintfHandler::HandleInvalidAmount(
5063                                       const analyze_printf::PrintfSpecifier &FS,
5064                                       const analyze_printf::OptionalAmount &Amt,
5065                                       unsigned type,
5066                                       const char *startSpecifier,
5067                                       unsigned specifierLen) {
5068   const analyze_printf::PrintfConversionSpecifier &CS =
5069     FS.getConversionSpecifier();
5070 
5071   FixItHint fixit =
5072     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5073       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5074                                  Amt.getConstantLength()))
5075       : FixItHint();
5076 
5077   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5078                          << type << CS.toString(),
5079                        getLocationOfByte(Amt.getStart()),
5080                        /*IsStringLocation*/true,
5081                        getSpecifierRange(startSpecifier, specifierLen),
5082                        fixit);
5083 }
5084 
5085 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5086                                     const analyze_printf::OptionalFlag &flag,
5087                                     const char *startSpecifier,
5088                                     unsigned specifierLen) {
5089   // Warn about pointless flag with a fixit removal.
5090   const analyze_printf::PrintfConversionSpecifier &CS =
5091     FS.getConversionSpecifier();
5092   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5093                          << flag.toString() << CS.toString(),
5094                        getLocationOfByte(flag.getPosition()),
5095                        /*IsStringLocation*/true,
5096                        getSpecifierRange(startSpecifier, specifierLen),
5097                        FixItHint::CreateRemoval(
5098                          getSpecifierRange(flag.getPosition(), 1)));
5099 }
5100 
5101 void CheckPrintfHandler::HandleIgnoredFlag(
5102                                 const analyze_printf::PrintfSpecifier &FS,
5103                                 const analyze_printf::OptionalFlag &ignoredFlag,
5104                                 const analyze_printf::OptionalFlag &flag,
5105                                 const char *startSpecifier,
5106                                 unsigned specifierLen) {
5107   // Warn about ignored flag with a fixit removal.
5108   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5109                          << ignoredFlag.toString() << flag.toString(),
5110                        getLocationOfByte(ignoredFlag.getPosition()),
5111                        /*IsStringLocation*/true,
5112                        getSpecifierRange(startSpecifier, specifierLen),
5113                        FixItHint::CreateRemoval(
5114                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5115 }
5116 
5117 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5118 //                            bool IsStringLocation, Range StringRange,
5119 //                            ArrayRef<FixItHint> Fixit = None);
5120 
5121 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5122                                                      unsigned flagLen) {
5123   // Warn about an empty flag.
5124   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5125                        getLocationOfByte(startFlag),
5126                        /*IsStringLocation*/true,
5127                        getSpecifierRange(startFlag, flagLen));
5128 }
5129 
5130 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5131                                                        unsigned flagLen) {
5132   // Warn about an invalid flag.
5133   auto Range = getSpecifierRange(startFlag, flagLen);
5134   StringRef flag(startFlag, flagLen);
5135   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5136                       getLocationOfByte(startFlag),
5137                       /*IsStringLocation*/true,
5138                       Range, FixItHint::CreateRemoval(Range));
5139 }
5140 
5141 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5142     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5143     // Warn about using '[...]' without a '@' conversion.
5144     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5145     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5146     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5147                          getLocationOfByte(conversionPosition),
5148                          /*IsStringLocation*/true,
5149                          Range, FixItHint::CreateRemoval(Range));
5150 }
5151 
5152 // Determines if the specified is a C++ class or struct containing
5153 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5154 // "c_str()").
5155 template<typename MemberKind>
5156 static llvm::SmallPtrSet<MemberKind*, 1>
5157 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5158   const RecordType *RT = Ty->getAs<RecordType>();
5159   llvm::SmallPtrSet<MemberKind*, 1> Results;
5160 
5161   if (!RT)
5162     return Results;
5163   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5164   if (!RD || !RD->getDefinition())
5165     return Results;
5166 
5167   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5168                  Sema::LookupMemberName);
5169   R.suppressDiagnostics();
5170 
5171   // We just need to include all members of the right kind turned up by the
5172   // filter, at this point.
5173   if (S.LookupQualifiedName(R, RT->getDecl()))
5174     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5175       NamedDecl *decl = (*I)->getUnderlyingDecl();
5176       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5177         Results.insert(FK);
5178     }
5179   return Results;
5180 }
5181 
5182 /// Check if we could call '.c_str()' on an object.
5183 ///
5184 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5185 /// allow the call, or if it would be ambiguous).
5186 bool Sema::hasCStrMethod(const Expr *E) {
5187   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5188   MethodSet Results =
5189       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5190   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5191        MI != ME; ++MI)
5192     if ((*MI)->getMinRequiredArguments() == 0)
5193       return true;
5194   return false;
5195 }
5196 
5197 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5198 // better diagnostic if so. AT is assumed to be valid.
5199 // Returns true when a c_str() conversion method is found.
5200 bool CheckPrintfHandler::checkForCStrMembers(
5201     const analyze_printf::ArgType &AT, const Expr *E) {
5202   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5203 
5204   MethodSet Results =
5205       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5206 
5207   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5208        MI != ME; ++MI) {
5209     const CXXMethodDecl *Method = *MI;
5210     if (Method->getMinRequiredArguments() == 0 &&
5211         AT.matchesType(S.Context, Method->getReturnType())) {
5212       // FIXME: Suggest parens if the expression needs them.
5213       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5214       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5215           << "c_str()"
5216           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5217       return true;
5218     }
5219   }
5220 
5221   return false;
5222 }
5223 
5224 bool
5225 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5226                                             &FS,
5227                                           const char *startSpecifier,
5228                                           unsigned specifierLen) {
5229   using namespace analyze_format_string;
5230   using namespace analyze_printf;
5231   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5232 
5233   if (FS.consumesDataArgument()) {
5234     if (atFirstArg) {
5235         atFirstArg = false;
5236         usesPositionalArgs = FS.usesPositionalArg();
5237     }
5238     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5239       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5240                                         startSpecifier, specifierLen);
5241       return false;
5242     }
5243   }
5244 
5245   // First check if the field width, precision, and conversion specifier
5246   // have matching data arguments.
5247   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5248                     startSpecifier, specifierLen)) {
5249     return false;
5250   }
5251 
5252   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5253                     startSpecifier, specifierLen)) {
5254     return false;
5255   }
5256 
5257   if (!CS.consumesDataArgument()) {
5258     // FIXME: Technically specifying a precision or field width here
5259     // makes no sense.  Worth issuing a warning at some point.
5260     return true;
5261   }
5262 
5263   // Consume the argument.
5264   unsigned argIndex = FS.getArgIndex();
5265   if (argIndex < NumDataArgs) {
5266     // The check to see if the argIndex is valid will come later.
5267     // We set the bit here because we may exit early from this
5268     // function if we encounter some other error.
5269     CoveredArgs.set(argIndex);
5270   }
5271 
5272   // FreeBSD kernel extensions.
5273   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5274       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5275     // We need at least two arguments.
5276     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5277       return false;
5278 
5279     // Claim the second argument.
5280     CoveredArgs.set(argIndex + 1);
5281 
5282     // Type check the first argument (int for %b, pointer for %D)
5283     const Expr *Ex = getDataArg(argIndex);
5284     const analyze_printf::ArgType &AT =
5285       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5286         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5287     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5288       EmitFormatDiagnostic(
5289         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5290         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5291         << false << Ex->getSourceRange(),
5292         Ex->getLocStart(), /*IsStringLocation*/false,
5293         getSpecifierRange(startSpecifier, specifierLen));
5294 
5295     // Type check the second argument (char * for both %b and %D)
5296     Ex = getDataArg(argIndex + 1);
5297     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5298     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5299       EmitFormatDiagnostic(
5300         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5301         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5302         << false << Ex->getSourceRange(),
5303         Ex->getLocStart(), /*IsStringLocation*/false,
5304         getSpecifierRange(startSpecifier, specifierLen));
5305 
5306      return true;
5307   }
5308 
5309   // Check for using an Objective-C specific conversion specifier
5310   // in a non-ObjC literal.
5311   if (!ObjCContext && CS.isObjCArg()) {
5312     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5313                                                   specifierLen);
5314   }
5315 
5316   // Check for invalid use of field width
5317   if (!FS.hasValidFieldWidth()) {
5318     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
5319         startSpecifier, specifierLen);
5320   }
5321 
5322   // Check for invalid use of precision
5323   if (!FS.hasValidPrecision()) {
5324     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
5325         startSpecifier, specifierLen);
5326   }
5327 
5328   // Check each flag does not conflict with any other component.
5329   if (!FS.hasValidThousandsGroupingPrefix())
5330     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
5331   if (!FS.hasValidLeadingZeros())
5332     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
5333   if (!FS.hasValidPlusPrefix())
5334     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
5335   if (!FS.hasValidSpacePrefix())
5336     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
5337   if (!FS.hasValidAlternativeForm())
5338     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
5339   if (!FS.hasValidLeftJustified())
5340     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
5341 
5342   // Check that flags are not ignored by another flag
5343   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
5344     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
5345         startSpecifier, specifierLen);
5346   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
5347     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
5348             startSpecifier, specifierLen);
5349 
5350   // Check the length modifier is valid with the given conversion specifier.
5351   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5352     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5353                                 diag::warn_format_nonsensical_length);
5354   else if (!FS.hasStandardLengthModifier())
5355     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5356   else if (!FS.hasStandardLengthConversionCombination())
5357     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5358                                 diag::warn_format_non_standard_conversion_spec);
5359 
5360   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5361     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5362 
5363   // The remaining checks depend on the data arguments.
5364   if (HasVAListArg)
5365     return true;
5366 
5367   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5368     return false;
5369 
5370   const Expr *Arg = getDataArg(argIndex);
5371   if (!Arg)
5372     return true;
5373 
5374   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5375 }
5376 
5377 static bool requiresParensToAddCast(const Expr *E) {
5378   // FIXME: We should have a general way to reason about operator
5379   // precedence and whether parens are actually needed here.
5380   // Take care of a few common cases where they aren't.
5381   const Expr *Inside = E->IgnoreImpCasts();
5382   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
5383     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
5384 
5385   switch (Inside->getStmtClass()) {
5386   case Stmt::ArraySubscriptExprClass:
5387   case Stmt::CallExprClass:
5388   case Stmt::CharacterLiteralClass:
5389   case Stmt::CXXBoolLiteralExprClass:
5390   case Stmt::DeclRefExprClass:
5391   case Stmt::FloatingLiteralClass:
5392   case Stmt::IntegerLiteralClass:
5393   case Stmt::MemberExprClass:
5394   case Stmt::ObjCArrayLiteralClass:
5395   case Stmt::ObjCBoolLiteralExprClass:
5396   case Stmt::ObjCBoxedExprClass:
5397   case Stmt::ObjCDictionaryLiteralClass:
5398   case Stmt::ObjCEncodeExprClass:
5399   case Stmt::ObjCIvarRefExprClass:
5400   case Stmt::ObjCMessageExprClass:
5401   case Stmt::ObjCPropertyRefExprClass:
5402   case Stmt::ObjCStringLiteralClass:
5403   case Stmt::ObjCSubscriptRefExprClass:
5404   case Stmt::ParenExprClass:
5405   case Stmt::StringLiteralClass:
5406   case Stmt::UnaryOperatorClass:
5407     return false;
5408   default:
5409     return true;
5410   }
5411 }
5412 
5413 static std::pair<QualType, StringRef>
5414 shouldNotPrintDirectly(const ASTContext &Context,
5415                        QualType IntendedTy,
5416                        const Expr *E) {
5417   // Use a 'while' to peel off layers of typedefs.
5418   QualType TyTy = IntendedTy;
5419   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
5420     StringRef Name = UserTy->getDecl()->getName();
5421     QualType CastTy = llvm::StringSwitch<QualType>(Name)
5422       .Case("NSInteger", Context.LongTy)
5423       .Case("NSUInteger", Context.UnsignedLongTy)
5424       .Case("SInt32", Context.IntTy)
5425       .Case("UInt32", Context.UnsignedIntTy)
5426       .Default(QualType());
5427 
5428     if (!CastTy.isNull())
5429       return std::make_pair(CastTy, Name);
5430 
5431     TyTy = UserTy->desugar();
5432   }
5433 
5434   // Strip parens if necessary.
5435   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
5436     return shouldNotPrintDirectly(Context,
5437                                   PE->getSubExpr()->getType(),
5438                                   PE->getSubExpr());
5439 
5440   // If this is a conditional expression, then its result type is constructed
5441   // via usual arithmetic conversions and thus there might be no necessary
5442   // typedef sugar there.  Recurse to operands to check for NSInteger &
5443   // Co. usage condition.
5444   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5445     QualType TrueTy, FalseTy;
5446     StringRef TrueName, FalseName;
5447 
5448     std::tie(TrueTy, TrueName) =
5449       shouldNotPrintDirectly(Context,
5450                              CO->getTrueExpr()->getType(),
5451                              CO->getTrueExpr());
5452     std::tie(FalseTy, FalseName) =
5453       shouldNotPrintDirectly(Context,
5454                              CO->getFalseExpr()->getType(),
5455                              CO->getFalseExpr());
5456 
5457     if (TrueTy == FalseTy)
5458       return std::make_pair(TrueTy, TrueName);
5459     else if (TrueTy.isNull())
5460       return std::make_pair(FalseTy, FalseName);
5461     else if (FalseTy.isNull())
5462       return std::make_pair(TrueTy, TrueName);
5463   }
5464 
5465   return std::make_pair(QualType(), StringRef());
5466 }
5467 
5468 bool
5469 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5470                                     const char *StartSpecifier,
5471                                     unsigned SpecifierLen,
5472                                     const Expr *E) {
5473   using namespace analyze_format_string;
5474   using namespace analyze_printf;
5475   // Now type check the data expression that matches the
5476   // format specifier.
5477   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
5478                                                     ObjCContext);
5479   if (!AT.isValid())
5480     return true;
5481 
5482   QualType ExprTy = E->getType();
5483   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
5484     ExprTy = TET->getUnderlyingExpr()->getType();
5485   }
5486 
5487   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
5488 
5489   if (match == analyze_printf::ArgType::Match) {
5490     return true;
5491   }
5492 
5493   // Look through argument promotions for our error message's reported type.
5494   // This includes the integral and floating promotions, but excludes array
5495   // and function pointer decay; seeing that an argument intended to be a
5496   // string has type 'char [6]' is probably more confusing than 'char *'.
5497   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5498     if (ICE->getCastKind() == CK_IntegralCast ||
5499         ICE->getCastKind() == CK_FloatingCast) {
5500       E = ICE->getSubExpr();
5501       ExprTy = E->getType();
5502 
5503       // Check if we didn't match because of an implicit cast from a 'char'
5504       // or 'short' to an 'int'.  This is done because printf is a varargs
5505       // function.
5506       if (ICE->getType() == S.Context.IntTy ||
5507           ICE->getType() == S.Context.UnsignedIntTy) {
5508         // All further checking is done on the subexpression.
5509         if (AT.matchesType(S.Context, ExprTy))
5510           return true;
5511       }
5512     }
5513   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
5514     // Special case for 'a', which has type 'int' in C.
5515     // Note, however, that we do /not/ want to treat multibyte constants like
5516     // 'MooV' as characters! This form is deprecated but still exists.
5517     if (ExprTy == S.Context.IntTy)
5518       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
5519         ExprTy = S.Context.CharTy;
5520   }
5521 
5522   // Look through enums to their underlying type.
5523   bool IsEnum = false;
5524   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
5525     ExprTy = EnumTy->getDecl()->getIntegerType();
5526     IsEnum = true;
5527   }
5528 
5529   // %C in an Objective-C context prints a unichar, not a wchar_t.
5530   // If the argument is an integer of some kind, believe the %C and suggest
5531   // a cast instead of changing the conversion specifier.
5532   QualType IntendedTy = ExprTy;
5533   if (ObjCContext &&
5534       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
5535     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
5536         !ExprTy->isCharType()) {
5537       // 'unichar' is defined as a typedef of unsigned short, but we should
5538       // prefer using the typedef if it is visible.
5539       IntendedTy = S.Context.UnsignedShortTy;
5540 
5541       // While we are here, check if the value is an IntegerLiteral that happens
5542       // to be within the valid range.
5543       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
5544         const llvm::APInt &V = IL->getValue();
5545         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
5546           return true;
5547       }
5548 
5549       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
5550                           Sema::LookupOrdinaryName);
5551       if (S.LookupName(Result, S.getCurScope())) {
5552         NamedDecl *ND = Result.getFoundDecl();
5553         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
5554           if (TD->getUnderlyingType() == IntendedTy)
5555             IntendedTy = S.Context.getTypedefType(TD);
5556       }
5557     }
5558   }
5559 
5560   // Special-case some of Darwin's platform-independence types by suggesting
5561   // casts to primitive types that are known to be large enough.
5562   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
5563   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
5564     QualType CastTy;
5565     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
5566     if (!CastTy.isNull()) {
5567       IntendedTy = CastTy;
5568       ShouldNotPrintDirectly = true;
5569     }
5570   }
5571 
5572   // We may be able to offer a FixItHint if it is a supported type.
5573   PrintfSpecifier fixedFS = FS;
5574   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
5575                                  S.Context, ObjCContext);
5576 
5577   if (success) {
5578     // Get the fix string from the fixed format specifier
5579     SmallString<16> buf;
5580     llvm::raw_svector_ostream os(buf);
5581     fixedFS.toString(os);
5582 
5583     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
5584 
5585     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
5586       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5587       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5588         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5589       }
5590       // In this case, the specifier is wrong and should be changed to match
5591       // the argument.
5592       EmitFormatDiagnostic(S.PDiag(diag)
5593                                << AT.getRepresentativeTypeName(S.Context)
5594                                << IntendedTy << IsEnum << E->getSourceRange(),
5595                            E->getLocStart(),
5596                            /*IsStringLocation*/ false, SpecRange,
5597                            FixItHint::CreateReplacement(SpecRange, os.str()));
5598     } else {
5599       // The canonical type for formatting this value is different from the
5600       // actual type of the expression. (This occurs, for example, with Darwin's
5601       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
5602       // should be printed as 'long' for 64-bit compatibility.)
5603       // Rather than emitting a normal format/argument mismatch, we want to
5604       // add a cast to the recommended type (and correct the format string
5605       // if necessary).
5606       SmallString<16> CastBuf;
5607       llvm::raw_svector_ostream CastFix(CastBuf);
5608       CastFix << "(";
5609       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
5610       CastFix << ")";
5611 
5612       SmallVector<FixItHint,4> Hints;
5613       if (!AT.matchesType(S.Context, IntendedTy))
5614         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
5615 
5616       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
5617         // If there's already a cast present, just replace it.
5618         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
5619         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
5620 
5621       } else if (!requiresParensToAddCast(E)) {
5622         // If the expression has high enough precedence,
5623         // just write the C-style cast.
5624         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5625                                                    CastFix.str()));
5626       } else {
5627         // Otherwise, add parens around the expression as well as the cast.
5628         CastFix << "(";
5629         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
5630                                                    CastFix.str()));
5631 
5632         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
5633         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
5634       }
5635 
5636       if (ShouldNotPrintDirectly) {
5637         // The expression has a type that should not be printed directly.
5638         // We extract the name from the typedef because we don't want to show
5639         // the underlying type in the diagnostic.
5640         StringRef Name;
5641         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
5642           Name = TypedefTy->getDecl()->getName();
5643         else
5644           Name = CastTyName;
5645         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
5646                                << Name << IntendedTy << IsEnum
5647                                << E->getSourceRange(),
5648                              E->getLocStart(), /*IsStringLocation=*/false,
5649                              SpecRange, Hints);
5650       } else {
5651         // In this case, the expression could be printed using a different
5652         // specifier, but we've decided that the specifier is probably correct
5653         // and we should cast instead. Just use the normal warning message.
5654         EmitFormatDiagnostic(
5655           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5656             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
5657             << E->getSourceRange(),
5658           E->getLocStart(), /*IsStringLocation*/false,
5659           SpecRange, Hints);
5660       }
5661     }
5662   } else {
5663     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
5664                                                    SpecifierLen);
5665     // Since the warning for passing non-POD types to variadic functions
5666     // was deferred until now, we emit a warning for non-POD
5667     // arguments here.
5668     switch (S.isValidVarArgType(ExprTy)) {
5669     case Sema::VAK_Valid:
5670     case Sema::VAK_ValidInCXX11: {
5671       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5672       if (match == analyze_printf::ArgType::NoMatchPedantic) {
5673         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5674       }
5675 
5676       EmitFormatDiagnostic(
5677           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
5678                         << IsEnum << CSR << E->getSourceRange(),
5679           E->getLocStart(), /*IsStringLocation*/ false, CSR);
5680       break;
5681     }
5682     case Sema::VAK_Undefined:
5683     case Sema::VAK_MSVCUndefined:
5684       EmitFormatDiagnostic(
5685         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
5686           << S.getLangOpts().CPlusPlus11
5687           << ExprTy
5688           << CallType
5689           << AT.getRepresentativeTypeName(S.Context)
5690           << CSR
5691           << E->getSourceRange(),
5692         E->getLocStart(), /*IsStringLocation*/false, CSR);
5693       checkForCStrMembers(AT, E);
5694       break;
5695 
5696     case Sema::VAK_Invalid:
5697       if (ExprTy->isObjCObjectType())
5698         EmitFormatDiagnostic(
5699           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
5700             << S.getLangOpts().CPlusPlus11
5701             << ExprTy
5702             << CallType
5703             << AT.getRepresentativeTypeName(S.Context)
5704             << CSR
5705             << E->getSourceRange(),
5706           E->getLocStart(), /*IsStringLocation*/false, CSR);
5707       else
5708         // FIXME: If this is an initializer list, suggest removing the braces
5709         // or inserting a cast to the target type.
5710         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
5711           << isa<InitListExpr>(E) << ExprTy << CallType
5712           << AT.getRepresentativeTypeName(S.Context)
5713           << E->getSourceRange();
5714       break;
5715     }
5716 
5717     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
5718            "format string specifier index out of range");
5719     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
5720   }
5721 
5722   return true;
5723 }
5724 
5725 //===--- CHECK: Scanf format string checking ------------------------------===//
5726 
5727 namespace {
5728 class CheckScanfHandler : public CheckFormatHandler {
5729 public:
5730   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
5731                     const Expr *origFormatExpr, unsigned firstDataArg,
5732                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
5733                     ArrayRef<const Expr *> Args,
5734                     unsigned formatIdx, bool inFunctionCall,
5735                     Sema::VariadicCallType CallType,
5736                     llvm::SmallBitVector &CheckedVarArgs,
5737                     UncoveredArgHandler &UncoveredArg)
5738     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
5739                          numDataArgs, beg, hasVAListArg,
5740                          Args, formatIdx, inFunctionCall, CallType,
5741                          CheckedVarArgs, UncoveredArg)
5742   {}
5743 
5744   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
5745                             const char *startSpecifier,
5746                             unsigned specifierLen) override;
5747 
5748   bool HandleInvalidScanfConversionSpecifier(
5749           const analyze_scanf::ScanfSpecifier &FS,
5750           const char *startSpecifier,
5751           unsigned specifierLen) override;
5752 
5753   void HandleIncompleteScanList(const char *start, const char *end) override;
5754 };
5755 } // end anonymous namespace
5756 
5757 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
5758                                                  const char *end) {
5759   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
5760                        getLocationOfByte(end), /*IsStringLocation*/true,
5761                        getSpecifierRange(start, end - start));
5762 }
5763 
5764 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
5765                                         const analyze_scanf::ScanfSpecifier &FS,
5766                                         const char *startSpecifier,
5767                                         unsigned specifierLen) {
5768 
5769   const analyze_scanf::ScanfConversionSpecifier &CS =
5770     FS.getConversionSpecifier();
5771 
5772   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5773                                           getLocationOfByte(CS.getStart()),
5774                                           startSpecifier, specifierLen,
5775                                           CS.getStart(), CS.getLength());
5776 }
5777 
5778 bool CheckScanfHandler::HandleScanfSpecifier(
5779                                        const analyze_scanf::ScanfSpecifier &FS,
5780                                        const char *startSpecifier,
5781                                        unsigned specifierLen) {
5782   using namespace analyze_scanf;
5783   using namespace analyze_format_string;
5784 
5785   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
5786 
5787   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
5788   // be used to decide if we are using positional arguments consistently.
5789   if (FS.consumesDataArgument()) {
5790     if (atFirstArg) {
5791       atFirstArg = false;
5792       usesPositionalArgs = FS.usesPositionalArg();
5793     }
5794     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5795       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5796                                         startSpecifier, specifierLen);
5797       return false;
5798     }
5799   }
5800 
5801   // Check if the field with is non-zero.
5802   const OptionalAmount &Amt = FS.getFieldWidth();
5803   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
5804     if (Amt.getConstantAmount() == 0) {
5805       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
5806                                                    Amt.getConstantLength());
5807       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
5808                            getLocationOfByte(Amt.getStart()),
5809                            /*IsStringLocation*/true, R,
5810                            FixItHint::CreateRemoval(R));
5811     }
5812   }
5813 
5814   if (!FS.consumesDataArgument()) {
5815     // FIXME: Technically specifying a precision or field width here
5816     // makes no sense.  Worth issuing a warning at some point.
5817     return true;
5818   }
5819 
5820   // Consume the argument.
5821   unsigned argIndex = FS.getArgIndex();
5822   if (argIndex < NumDataArgs) {
5823       // The check to see if the argIndex is valid will come later.
5824       // We set the bit here because we may exit early from this
5825       // function if we encounter some other error.
5826     CoveredArgs.set(argIndex);
5827   }
5828 
5829   // Check the length modifier is valid with the given conversion specifier.
5830   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5831     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5832                                 diag::warn_format_nonsensical_length);
5833   else if (!FS.hasStandardLengthModifier())
5834     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5835   else if (!FS.hasStandardLengthConversionCombination())
5836     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5837                                 diag::warn_format_non_standard_conversion_spec);
5838 
5839   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5840     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5841 
5842   // The remaining checks depend on the data arguments.
5843   if (HasVAListArg)
5844     return true;
5845 
5846   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5847     return false;
5848 
5849   // Check that the argument type matches the format specifier.
5850   const Expr *Ex = getDataArg(argIndex);
5851   if (!Ex)
5852     return true;
5853 
5854   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
5855 
5856   if (!AT.isValid()) {
5857     return true;
5858   }
5859 
5860   analyze_format_string::ArgType::MatchKind match =
5861       AT.matchesType(S.Context, Ex->getType());
5862   if (match == analyze_format_string::ArgType::Match) {
5863     return true;
5864   }
5865 
5866   ScanfSpecifier fixedFS = FS;
5867   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5868                                  S.getLangOpts(), S.Context);
5869 
5870   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5871   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5872     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5873   }
5874 
5875   if (success) {
5876     // Get the fix string from the fixed format specifier.
5877     SmallString<128> buf;
5878     llvm::raw_svector_ostream os(buf);
5879     fixedFS.toString(os);
5880 
5881     EmitFormatDiagnostic(
5882         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5883                       << Ex->getType() << false << Ex->getSourceRange(),
5884         Ex->getLocStart(),
5885         /*IsStringLocation*/ false,
5886         getSpecifierRange(startSpecifier, specifierLen),
5887         FixItHint::CreateReplacement(
5888             getSpecifierRange(startSpecifier, specifierLen), os.str()));
5889   } else {
5890     EmitFormatDiagnostic(S.PDiag(diag)
5891                              << AT.getRepresentativeTypeName(S.Context)
5892                              << Ex->getType() << false << Ex->getSourceRange(),
5893                          Ex->getLocStart(),
5894                          /*IsStringLocation*/ false,
5895                          getSpecifierRange(startSpecifier, specifierLen));
5896   }
5897 
5898   return true;
5899 }
5900 
5901 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
5902                               const Expr *OrigFormatExpr,
5903                               ArrayRef<const Expr *> Args,
5904                               bool HasVAListArg, unsigned format_idx,
5905                               unsigned firstDataArg,
5906                               Sema::FormatStringType Type,
5907                               bool inFunctionCall,
5908                               Sema::VariadicCallType CallType,
5909                               llvm::SmallBitVector &CheckedVarArgs,
5910                               UncoveredArgHandler &UncoveredArg) {
5911   // CHECK: is the format string a wide literal?
5912   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
5913     CheckFormatHandler::EmitFormatDiagnostic(
5914       S, inFunctionCall, Args[format_idx],
5915       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
5916       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5917     return;
5918   }
5919 
5920   // Str - The format string.  NOTE: this is NOT null-terminated!
5921   StringRef StrRef = FExpr->getString();
5922   const char *Str = StrRef.data();
5923   // Account for cases where the string literal is truncated in a declaration.
5924   const ConstantArrayType *T =
5925     S.Context.getAsConstantArrayType(FExpr->getType());
5926   assert(T && "String literal not of constant array type!");
5927   size_t TypeSize = T->getSize().getZExtValue();
5928   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5929   const unsigned numDataArgs = Args.size() - firstDataArg;
5930 
5931   // Emit a warning if the string literal is truncated and does not contain an
5932   // embedded null character.
5933   if (TypeSize <= StrRef.size() &&
5934       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5935     CheckFormatHandler::EmitFormatDiagnostic(
5936         S, inFunctionCall, Args[format_idx],
5937         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
5938         FExpr->getLocStart(),
5939         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5940     return;
5941   }
5942 
5943   // CHECK: empty format string?
5944   if (StrLen == 0 && numDataArgs > 0) {
5945     CheckFormatHandler::EmitFormatDiagnostic(
5946       S, inFunctionCall, Args[format_idx],
5947       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
5948       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5949     return;
5950   }
5951 
5952   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5953       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5954     CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5955                          numDataArgs, (Type == Sema::FST_NSString ||
5956                                        Type == Sema::FST_OSTrace),
5957                          Str, HasVAListArg, Args, format_idx,
5958                          inFunctionCall, CallType, CheckedVarArgs,
5959                          UncoveredArg);
5960 
5961     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
5962                                                   S.getLangOpts(),
5963                                                   S.Context.getTargetInfo(),
5964                                             Type == Sema::FST_FreeBSDKPrintf))
5965       H.DoneProcessing();
5966   } else if (Type == Sema::FST_Scanf) {
5967     CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5968                         Str, HasVAListArg, Args, format_idx,
5969                         inFunctionCall, CallType, CheckedVarArgs,
5970                         UncoveredArg);
5971 
5972     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
5973                                                  S.getLangOpts(),
5974                                                  S.Context.getTargetInfo()))
5975       H.DoneProcessing();
5976   } // TODO: handle other formats
5977 }
5978 
5979 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5980   // Str - The format string.  NOTE: this is NOT null-terminated!
5981   StringRef StrRef = FExpr->getString();
5982   const char *Str = StrRef.data();
5983   // Account for cases where the string literal is truncated in a declaration.
5984   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5985   assert(T && "String literal not of constant array type!");
5986   size_t TypeSize = T->getSize().getZExtValue();
5987   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5988   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5989                                                          getLangOpts(),
5990                                                          Context.getTargetInfo());
5991 }
5992 
5993 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5994 
5995 // Returns the related absolute value function that is larger, of 0 if one
5996 // does not exist.
5997 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5998   switch (AbsFunction) {
5999   default:
6000     return 0;
6001 
6002   case Builtin::BI__builtin_abs:
6003     return Builtin::BI__builtin_labs;
6004   case Builtin::BI__builtin_labs:
6005     return Builtin::BI__builtin_llabs;
6006   case Builtin::BI__builtin_llabs:
6007     return 0;
6008 
6009   case Builtin::BI__builtin_fabsf:
6010     return Builtin::BI__builtin_fabs;
6011   case Builtin::BI__builtin_fabs:
6012     return Builtin::BI__builtin_fabsl;
6013   case Builtin::BI__builtin_fabsl:
6014     return 0;
6015 
6016   case Builtin::BI__builtin_cabsf:
6017     return Builtin::BI__builtin_cabs;
6018   case Builtin::BI__builtin_cabs:
6019     return Builtin::BI__builtin_cabsl;
6020   case Builtin::BI__builtin_cabsl:
6021     return 0;
6022 
6023   case Builtin::BIabs:
6024     return Builtin::BIlabs;
6025   case Builtin::BIlabs:
6026     return Builtin::BIllabs;
6027   case Builtin::BIllabs:
6028     return 0;
6029 
6030   case Builtin::BIfabsf:
6031     return Builtin::BIfabs;
6032   case Builtin::BIfabs:
6033     return Builtin::BIfabsl;
6034   case Builtin::BIfabsl:
6035     return 0;
6036 
6037   case Builtin::BIcabsf:
6038    return Builtin::BIcabs;
6039   case Builtin::BIcabs:
6040     return Builtin::BIcabsl;
6041   case Builtin::BIcabsl:
6042     return 0;
6043   }
6044 }
6045 
6046 // Returns the argument type of the absolute value function.
6047 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6048                                              unsigned AbsType) {
6049   if (AbsType == 0)
6050     return QualType();
6051 
6052   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6053   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6054   if (Error != ASTContext::GE_None)
6055     return QualType();
6056 
6057   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6058   if (!FT)
6059     return QualType();
6060 
6061   if (FT->getNumParams() != 1)
6062     return QualType();
6063 
6064   return FT->getParamType(0);
6065 }
6066 
6067 // Returns the best absolute value function, or zero, based on type and
6068 // current absolute value function.
6069 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6070                                    unsigned AbsFunctionKind) {
6071   unsigned BestKind = 0;
6072   uint64_t ArgSize = Context.getTypeSize(ArgType);
6073   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6074        Kind = getLargerAbsoluteValueFunction(Kind)) {
6075     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6076     if (Context.getTypeSize(ParamType) >= ArgSize) {
6077       if (BestKind == 0)
6078         BestKind = Kind;
6079       else if (Context.hasSameType(ParamType, ArgType)) {
6080         BestKind = Kind;
6081         break;
6082       }
6083     }
6084   }
6085   return BestKind;
6086 }
6087 
6088 enum AbsoluteValueKind {
6089   AVK_Integer,
6090   AVK_Floating,
6091   AVK_Complex
6092 };
6093 
6094 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6095   if (T->isIntegralOrEnumerationType())
6096     return AVK_Integer;
6097   if (T->isRealFloatingType())
6098     return AVK_Floating;
6099   if (T->isAnyComplexType())
6100     return AVK_Complex;
6101 
6102   llvm_unreachable("Type not integer, floating, or complex");
6103 }
6104 
6105 // Changes the absolute value function to a different type.  Preserves whether
6106 // the function is a builtin.
6107 static unsigned changeAbsFunction(unsigned AbsKind,
6108                                   AbsoluteValueKind ValueKind) {
6109   switch (ValueKind) {
6110   case AVK_Integer:
6111     switch (AbsKind) {
6112     default:
6113       return 0;
6114     case Builtin::BI__builtin_fabsf:
6115     case Builtin::BI__builtin_fabs:
6116     case Builtin::BI__builtin_fabsl:
6117     case Builtin::BI__builtin_cabsf:
6118     case Builtin::BI__builtin_cabs:
6119     case Builtin::BI__builtin_cabsl:
6120       return Builtin::BI__builtin_abs;
6121     case Builtin::BIfabsf:
6122     case Builtin::BIfabs:
6123     case Builtin::BIfabsl:
6124     case Builtin::BIcabsf:
6125     case Builtin::BIcabs:
6126     case Builtin::BIcabsl:
6127       return Builtin::BIabs;
6128     }
6129   case AVK_Floating:
6130     switch (AbsKind) {
6131     default:
6132       return 0;
6133     case Builtin::BI__builtin_abs:
6134     case Builtin::BI__builtin_labs:
6135     case Builtin::BI__builtin_llabs:
6136     case Builtin::BI__builtin_cabsf:
6137     case Builtin::BI__builtin_cabs:
6138     case Builtin::BI__builtin_cabsl:
6139       return Builtin::BI__builtin_fabsf;
6140     case Builtin::BIabs:
6141     case Builtin::BIlabs:
6142     case Builtin::BIllabs:
6143     case Builtin::BIcabsf:
6144     case Builtin::BIcabs:
6145     case Builtin::BIcabsl:
6146       return Builtin::BIfabsf;
6147     }
6148   case AVK_Complex:
6149     switch (AbsKind) {
6150     default:
6151       return 0;
6152     case Builtin::BI__builtin_abs:
6153     case Builtin::BI__builtin_labs:
6154     case Builtin::BI__builtin_llabs:
6155     case Builtin::BI__builtin_fabsf:
6156     case Builtin::BI__builtin_fabs:
6157     case Builtin::BI__builtin_fabsl:
6158       return Builtin::BI__builtin_cabsf;
6159     case Builtin::BIabs:
6160     case Builtin::BIlabs:
6161     case Builtin::BIllabs:
6162     case Builtin::BIfabsf:
6163     case Builtin::BIfabs:
6164     case Builtin::BIfabsl:
6165       return Builtin::BIcabsf;
6166     }
6167   }
6168   llvm_unreachable("Unable to convert function");
6169 }
6170 
6171 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6172   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6173   if (!FnInfo)
6174     return 0;
6175 
6176   switch (FDecl->getBuiltinID()) {
6177   default:
6178     return 0;
6179   case Builtin::BI__builtin_abs:
6180   case Builtin::BI__builtin_fabs:
6181   case Builtin::BI__builtin_fabsf:
6182   case Builtin::BI__builtin_fabsl:
6183   case Builtin::BI__builtin_labs:
6184   case Builtin::BI__builtin_llabs:
6185   case Builtin::BI__builtin_cabs:
6186   case Builtin::BI__builtin_cabsf:
6187   case Builtin::BI__builtin_cabsl:
6188   case Builtin::BIabs:
6189   case Builtin::BIlabs:
6190   case Builtin::BIllabs:
6191   case Builtin::BIfabs:
6192   case Builtin::BIfabsf:
6193   case Builtin::BIfabsl:
6194   case Builtin::BIcabs:
6195   case Builtin::BIcabsf:
6196   case Builtin::BIcabsl:
6197     return FDecl->getBuiltinID();
6198   }
6199   llvm_unreachable("Unknown Builtin type");
6200 }
6201 
6202 // If the replacement is valid, emit a note with replacement function.
6203 // Additionally, suggest including the proper header if not already included.
6204 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6205                             unsigned AbsKind, QualType ArgType) {
6206   bool EmitHeaderHint = true;
6207   const char *HeaderName = nullptr;
6208   const char *FunctionName = nullptr;
6209   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6210     FunctionName = "std::abs";
6211     if (ArgType->isIntegralOrEnumerationType()) {
6212       HeaderName = "cstdlib";
6213     } else if (ArgType->isRealFloatingType()) {
6214       HeaderName = "cmath";
6215     } else {
6216       llvm_unreachable("Invalid Type");
6217     }
6218 
6219     // Lookup all std::abs
6220     if (NamespaceDecl *Std = S.getStdNamespace()) {
6221       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6222       R.suppressDiagnostics();
6223       S.LookupQualifiedName(R, Std);
6224 
6225       for (const auto *I : R) {
6226         const FunctionDecl *FDecl = nullptr;
6227         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6228           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6229         } else {
6230           FDecl = dyn_cast<FunctionDecl>(I);
6231         }
6232         if (!FDecl)
6233           continue;
6234 
6235         // Found std::abs(), check that they are the right ones.
6236         if (FDecl->getNumParams() != 1)
6237           continue;
6238 
6239         // Check that the parameter type can handle the argument.
6240         QualType ParamType = FDecl->getParamDecl(0)->getType();
6241         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6242             S.Context.getTypeSize(ArgType) <=
6243                 S.Context.getTypeSize(ParamType)) {
6244           // Found a function, don't need the header hint.
6245           EmitHeaderHint = false;
6246           break;
6247         }
6248       }
6249     }
6250   } else {
6251     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6252     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6253 
6254     if (HeaderName) {
6255       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6256       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6257       R.suppressDiagnostics();
6258       S.LookupName(R, S.getCurScope());
6259 
6260       if (R.isSingleResult()) {
6261         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6262         if (FD && FD->getBuiltinID() == AbsKind) {
6263           EmitHeaderHint = false;
6264         } else {
6265           return;
6266         }
6267       } else if (!R.empty()) {
6268         return;
6269       }
6270     }
6271   }
6272 
6273   S.Diag(Loc, diag::note_replace_abs_function)
6274       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
6275 
6276   if (!HeaderName)
6277     return;
6278 
6279   if (!EmitHeaderHint)
6280     return;
6281 
6282   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6283                                                     << FunctionName;
6284 }
6285 
6286 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
6287   if (!FDecl)
6288     return false;
6289 
6290   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
6291     return false;
6292 
6293   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
6294 
6295   while (ND && ND->isInlineNamespace()) {
6296     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
6297   }
6298 
6299   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
6300     return false;
6301 
6302   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
6303     return false;
6304 
6305   return true;
6306 }
6307 
6308 // Warn when using the wrong abs() function.
6309 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
6310                                       const FunctionDecl *FDecl,
6311                                       IdentifierInfo *FnInfo) {
6312   if (Call->getNumArgs() != 1)
6313     return;
6314 
6315   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
6316   bool IsStdAbs = IsFunctionStdAbs(FDecl);
6317   if (AbsKind == 0 && !IsStdAbs)
6318     return;
6319 
6320   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6321   QualType ParamType = Call->getArg(0)->getType();
6322 
6323   // Unsigned types cannot be negative.  Suggest removing the absolute value
6324   // function call.
6325   if (ArgType->isUnsignedIntegerType()) {
6326     const char *FunctionName =
6327         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
6328     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6329     Diag(Call->getExprLoc(), diag::note_remove_abs)
6330         << FunctionName
6331         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
6332     return;
6333   }
6334 
6335   // Taking the absolute value of a pointer is very suspicious, they probably
6336   // wanted to index into an array, dereference a pointer, call a function, etc.
6337   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
6338     unsigned DiagType = 0;
6339     if (ArgType->isFunctionType())
6340       DiagType = 1;
6341     else if (ArgType->isArrayType())
6342       DiagType = 2;
6343 
6344     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6345     return;
6346   }
6347 
6348   // std::abs has overloads which prevent most of the absolute value problems
6349   // from occurring.
6350   if (IsStdAbs)
6351     return;
6352 
6353   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
6354   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
6355 
6356   // The argument and parameter are the same kind.  Check if they are the right
6357   // size.
6358   if (ArgValueKind == ParamValueKind) {
6359     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
6360       return;
6361 
6362     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
6363     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
6364         << FDecl << ArgType << ParamType;
6365 
6366     if (NewAbsKind == 0)
6367       return;
6368 
6369     emitReplacement(*this, Call->getExprLoc(),
6370                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6371     return;
6372   }
6373 
6374   // ArgValueKind != ParamValueKind
6375   // The wrong type of absolute value function was used.  Attempt to find the
6376   // proper one.
6377   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
6378   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
6379   if (NewAbsKind == 0)
6380     return;
6381 
6382   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
6383       << FDecl << ParamValueKind << ArgValueKind;
6384 
6385   emitReplacement(*this, Call->getExprLoc(),
6386                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
6387 }
6388 
6389 //===--- CHECK: Standard memory functions ---------------------------------===//
6390 
6391 /// \brief Takes the expression passed to the size_t parameter of functions
6392 /// such as memcmp, strncat, etc and warns if it's a comparison.
6393 ///
6394 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
6395 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
6396                                            IdentifierInfo *FnName,
6397                                            SourceLocation FnLoc,
6398                                            SourceLocation RParenLoc) {
6399   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
6400   if (!Size)
6401     return false;
6402 
6403   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
6404   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
6405     return false;
6406 
6407   SourceRange SizeRange = Size->getSourceRange();
6408   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
6409       << SizeRange << FnName;
6410   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
6411       << FnName << FixItHint::CreateInsertion(
6412                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
6413       << FixItHint::CreateRemoval(RParenLoc);
6414   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
6415       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
6416       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
6417                                     ")");
6418 
6419   return true;
6420 }
6421 
6422 /// \brief Determine whether the given type is or contains a dynamic class type
6423 /// (e.g., whether it has a vtable).
6424 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
6425                                                      bool &IsContained) {
6426   // Look through array types while ignoring qualifiers.
6427   const Type *Ty = T->getBaseElementTypeUnsafe();
6428   IsContained = false;
6429 
6430   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
6431   RD = RD ? RD->getDefinition() : nullptr;
6432   if (!RD || RD->isInvalidDecl())
6433     return nullptr;
6434 
6435   if (RD->isDynamicClass())
6436     return RD;
6437 
6438   // Check all the fields.  If any bases were dynamic, the class is dynamic.
6439   // It's impossible for a class to transitively contain itself by value, so
6440   // infinite recursion is impossible.
6441   for (auto *FD : RD->fields()) {
6442     bool SubContained;
6443     if (const CXXRecordDecl *ContainedRD =
6444             getContainedDynamicClass(FD->getType(), SubContained)) {
6445       IsContained = true;
6446       return ContainedRD;
6447     }
6448   }
6449 
6450   return nullptr;
6451 }
6452 
6453 /// \brief If E is a sizeof expression, returns its argument expression,
6454 /// otherwise returns NULL.
6455 static const Expr *getSizeOfExprArg(const Expr *E) {
6456   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6457       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6458     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
6459       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
6460 
6461   return nullptr;
6462 }
6463 
6464 /// \brief If E is a sizeof expression, returns its argument type.
6465 static QualType getSizeOfArgType(const Expr *E) {
6466   if (const UnaryExprOrTypeTraitExpr *SizeOf =
6467       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
6468     if (SizeOf->getKind() == clang::UETT_SizeOf)
6469       return SizeOf->getTypeOfArgument();
6470 
6471   return QualType();
6472 }
6473 
6474 /// \brief Check for dangerous or invalid arguments to memset().
6475 ///
6476 /// This issues warnings on known problematic, dangerous or unspecified
6477 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
6478 /// function calls.
6479 ///
6480 /// \param Call The call expression to diagnose.
6481 void Sema::CheckMemaccessArguments(const CallExpr *Call,
6482                                    unsigned BId,
6483                                    IdentifierInfo *FnName) {
6484   assert(BId != 0);
6485 
6486   // It is possible to have a non-standard definition of memset.  Validate
6487   // we have enough arguments, and if not, abort further checking.
6488   unsigned ExpectedNumArgs =
6489       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
6490   if (Call->getNumArgs() < ExpectedNumArgs)
6491     return;
6492 
6493   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
6494                       BId == Builtin::BIstrndup ? 1 : 2);
6495   unsigned LenArg =
6496       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
6497   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
6498 
6499   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
6500                                      Call->getLocStart(), Call->getRParenLoc()))
6501     return;
6502 
6503   // We have special checking when the length is a sizeof expression.
6504   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
6505   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
6506   llvm::FoldingSetNodeID SizeOfArgID;
6507 
6508   // Although widely used, 'bzero' is not a standard function. Be more strict
6509   // with the argument types before allowing diagnostics and only allow the
6510   // form bzero(ptr, sizeof(...)).
6511   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
6512   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
6513     return;
6514 
6515   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
6516     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
6517     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
6518 
6519     QualType DestTy = Dest->getType();
6520     QualType PointeeTy;
6521     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
6522       PointeeTy = DestPtrTy->getPointeeType();
6523 
6524       // Never warn about void type pointers. This can be used to suppress
6525       // false positives.
6526       if (PointeeTy->isVoidType())
6527         continue;
6528 
6529       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
6530       // actually comparing the expressions for equality. Because computing the
6531       // expression IDs can be expensive, we only do this if the diagnostic is
6532       // enabled.
6533       if (SizeOfArg &&
6534           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
6535                            SizeOfArg->getExprLoc())) {
6536         // We only compute IDs for expressions if the warning is enabled, and
6537         // cache the sizeof arg's ID.
6538         if (SizeOfArgID == llvm::FoldingSetNodeID())
6539           SizeOfArg->Profile(SizeOfArgID, Context, true);
6540         llvm::FoldingSetNodeID DestID;
6541         Dest->Profile(DestID, Context, true);
6542         if (DestID == SizeOfArgID) {
6543           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
6544           //       over sizeof(src) as well.
6545           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
6546           StringRef ReadableName = FnName->getName();
6547 
6548           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
6549             if (UnaryOp->getOpcode() == UO_AddrOf)
6550               ActionIdx = 1; // If its an address-of operator, just remove it.
6551           if (!PointeeTy->isIncompleteType() &&
6552               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
6553             ActionIdx = 2; // If the pointee's size is sizeof(char),
6554                            // suggest an explicit length.
6555 
6556           // If the function is defined as a builtin macro, do not show macro
6557           // expansion.
6558           SourceLocation SL = SizeOfArg->getExprLoc();
6559           SourceRange DSR = Dest->getSourceRange();
6560           SourceRange SSR = SizeOfArg->getSourceRange();
6561           SourceManager &SM = getSourceManager();
6562 
6563           if (SM.isMacroArgExpansion(SL)) {
6564             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
6565             SL = SM.getSpellingLoc(SL);
6566             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
6567                              SM.getSpellingLoc(DSR.getEnd()));
6568             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
6569                              SM.getSpellingLoc(SSR.getEnd()));
6570           }
6571 
6572           DiagRuntimeBehavior(SL, SizeOfArg,
6573                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
6574                                 << ReadableName
6575                                 << PointeeTy
6576                                 << DestTy
6577                                 << DSR
6578                                 << SSR);
6579           DiagRuntimeBehavior(SL, SizeOfArg,
6580                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
6581                                 << ActionIdx
6582                                 << SSR);
6583 
6584           break;
6585         }
6586       }
6587 
6588       // Also check for cases where the sizeof argument is the exact same
6589       // type as the memory argument, and where it points to a user-defined
6590       // record type.
6591       if (SizeOfArgTy != QualType()) {
6592         if (PointeeTy->isRecordType() &&
6593             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
6594           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
6595                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
6596                                 << FnName << SizeOfArgTy << ArgIdx
6597                                 << PointeeTy << Dest->getSourceRange()
6598                                 << LenExpr->getSourceRange());
6599           break;
6600         }
6601       }
6602     } else if (DestTy->isArrayType()) {
6603       PointeeTy = DestTy;
6604     }
6605 
6606     if (PointeeTy == QualType())
6607       continue;
6608 
6609     // Always complain about dynamic classes.
6610     bool IsContained;
6611     if (const CXXRecordDecl *ContainedRD =
6612             getContainedDynamicClass(PointeeTy, IsContained)) {
6613 
6614       unsigned OperationType = 0;
6615       // "overwritten" if we're warning about the destination for any call
6616       // but memcmp; otherwise a verb appropriate to the call.
6617       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
6618         if (BId == Builtin::BImemcpy)
6619           OperationType = 1;
6620         else if(BId == Builtin::BImemmove)
6621           OperationType = 2;
6622         else if (BId == Builtin::BImemcmp)
6623           OperationType = 3;
6624       }
6625 
6626       DiagRuntimeBehavior(
6627         Dest->getExprLoc(), Dest,
6628         PDiag(diag::warn_dyn_class_memaccess)
6629           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
6630           << FnName << IsContained << ContainedRD << OperationType
6631           << Call->getCallee()->getSourceRange());
6632     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
6633              BId != Builtin::BImemset)
6634       DiagRuntimeBehavior(
6635         Dest->getExprLoc(), Dest,
6636         PDiag(diag::warn_arc_object_memaccess)
6637           << ArgIdx << FnName << PointeeTy
6638           << Call->getCallee()->getSourceRange());
6639     else
6640       continue;
6641 
6642     DiagRuntimeBehavior(
6643       Dest->getExprLoc(), Dest,
6644       PDiag(diag::note_bad_memaccess_silence)
6645         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
6646     break;
6647   }
6648 }
6649 
6650 // A little helper routine: ignore addition and subtraction of integer literals.
6651 // This intentionally does not ignore all integer constant expressions because
6652 // we don't want to remove sizeof().
6653 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
6654   Ex = Ex->IgnoreParenCasts();
6655 
6656   for (;;) {
6657     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
6658     if (!BO || !BO->isAdditiveOp())
6659       break;
6660 
6661     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
6662     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
6663 
6664     if (isa<IntegerLiteral>(RHS))
6665       Ex = LHS;
6666     else if (isa<IntegerLiteral>(LHS))
6667       Ex = RHS;
6668     else
6669       break;
6670   }
6671 
6672   return Ex;
6673 }
6674 
6675 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
6676                                                       ASTContext &Context) {
6677   // Only handle constant-sized or VLAs, but not flexible members.
6678   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
6679     // Only issue the FIXIT for arrays of size > 1.
6680     if (CAT->getSize().getSExtValue() <= 1)
6681       return false;
6682   } else if (!Ty->isVariableArrayType()) {
6683     return false;
6684   }
6685   return true;
6686 }
6687 
6688 // Warn if the user has made the 'size' argument to strlcpy or strlcat
6689 // be the size of the source, instead of the destination.
6690 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
6691                                     IdentifierInfo *FnName) {
6692 
6693   // Don't crash if the user has the wrong number of arguments
6694   unsigned NumArgs = Call->getNumArgs();
6695   if ((NumArgs != 3) && (NumArgs != 4))
6696     return;
6697 
6698   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
6699   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
6700   const Expr *CompareWithSrc = nullptr;
6701 
6702   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
6703                                      Call->getLocStart(), Call->getRParenLoc()))
6704     return;
6705 
6706   // Look for 'strlcpy(dst, x, sizeof(x))'
6707   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
6708     CompareWithSrc = Ex;
6709   else {
6710     // Look for 'strlcpy(dst, x, strlen(x))'
6711     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
6712       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
6713           SizeCall->getNumArgs() == 1)
6714         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
6715     }
6716   }
6717 
6718   if (!CompareWithSrc)
6719     return;
6720 
6721   // Determine if the argument to sizeof/strlen is equal to the source
6722   // argument.  In principle there's all kinds of things you could do
6723   // here, for instance creating an == expression and evaluating it with
6724   // EvaluateAsBooleanCondition, but this uses a more direct technique:
6725   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
6726   if (!SrcArgDRE)
6727     return;
6728 
6729   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
6730   if (!CompareWithSrcDRE ||
6731       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
6732     return;
6733 
6734   const Expr *OriginalSizeArg = Call->getArg(2);
6735   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
6736     << OriginalSizeArg->getSourceRange() << FnName;
6737 
6738   // Output a FIXIT hint if the destination is an array (rather than a
6739   // pointer to an array).  This could be enhanced to handle some
6740   // pointers if we know the actual size, like if DstArg is 'array+2'
6741   // we could say 'sizeof(array)-2'.
6742   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
6743   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
6744     return;
6745 
6746   SmallString<128> sizeString;
6747   llvm::raw_svector_ostream OS(sizeString);
6748   OS << "sizeof(";
6749   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6750   OS << ")";
6751 
6752   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
6753     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
6754                                     OS.str());
6755 }
6756 
6757 /// Check if two expressions refer to the same declaration.
6758 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
6759   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
6760     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
6761       return D1->getDecl() == D2->getDecl();
6762   return false;
6763 }
6764 
6765 static const Expr *getStrlenExprArg(const Expr *E) {
6766   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6767     const FunctionDecl *FD = CE->getDirectCallee();
6768     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
6769       return nullptr;
6770     return CE->getArg(0)->IgnoreParenCasts();
6771   }
6772   return nullptr;
6773 }
6774 
6775 // Warn on anti-patterns as the 'size' argument to strncat.
6776 // The correct size argument should look like following:
6777 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
6778 void Sema::CheckStrncatArguments(const CallExpr *CE,
6779                                  IdentifierInfo *FnName) {
6780   // Don't crash if the user has the wrong number of arguments.
6781   if (CE->getNumArgs() < 3)
6782     return;
6783   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
6784   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
6785   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
6786 
6787   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
6788                                      CE->getRParenLoc()))
6789     return;
6790 
6791   // Identify common expressions, which are wrongly used as the size argument
6792   // to strncat and may lead to buffer overflows.
6793   unsigned PatternType = 0;
6794   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
6795     // - sizeof(dst)
6796     if (referToTheSameDecl(SizeOfArg, DstArg))
6797       PatternType = 1;
6798     // - sizeof(src)
6799     else if (referToTheSameDecl(SizeOfArg, SrcArg))
6800       PatternType = 2;
6801   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
6802     if (BE->getOpcode() == BO_Sub) {
6803       const Expr *L = BE->getLHS()->IgnoreParenCasts();
6804       const Expr *R = BE->getRHS()->IgnoreParenCasts();
6805       // - sizeof(dst) - strlen(dst)
6806       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
6807           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
6808         PatternType = 1;
6809       // - sizeof(src) - (anything)
6810       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
6811         PatternType = 2;
6812     }
6813   }
6814 
6815   if (PatternType == 0)
6816     return;
6817 
6818   // Generate the diagnostic.
6819   SourceLocation SL = LenArg->getLocStart();
6820   SourceRange SR = LenArg->getSourceRange();
6821   SourceManager &SM = getSourceManager();
6822 
6823   // If the function is defined as a builtin macro, do not show macro expansion.
6824   if (SM.isMacroArgExpansion(SL)) {
6825     SL = SM.getSpellingLoc(SL);
6826     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6827                      SM.getSpellingLoc(SR.getEnd()));
6828   }
6829 
6830   // Check if the destination is an array (rather than a pointer to an array).
6831   QualType DstTy = DstArg->getType();
6832   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6833                                                                     Context);
6834   if (!isKnownSizeArray) {
6835     if (PatternType == 1)
6836       Diag(SL, diag::warn_strncat_wrong_size) << SR;
6837     else
6838       Diag(SL, diag::warn_strncat_src_size) << SR;
6839     return;
6840   }
6841 
6842   if (PatternType == 1)
6843     Diag(SL, diag::warn_strncat_large_size) << SR;
6844   else
6845     Diag(SL, diag::warn_strncat_src_size) << SR;
6846 
6847   SmallString<128> sizeString;
6848   llvm::raw_svector_ostream OS(sizeString);
6849   OS << "sizeof(";
6850   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6851   OS << ") - ";
6852   OS << "strlen(";
6853   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6854   OS << ") - 1";
6855 
6856   Diag(SL, diag::note_strncat_wrong_size)
6857     << FixItHint::CreateReplacement(SR, OS.str());
6858 }
6859 
6860 //===--- CHECK: Return Address of Stack Variable --------------------------===//
6861 
6862 static const Expr *EvalVal(const Expr *E,
6863                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6864                            const Decl *ParentDecl);
6865 static const Expr *EvalAddr(const Expr *E,
6866                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6867                             const Decl *ParentDecl);
6868 
6869 /// CheckReturnStackAddr - Check if a return statement returns the address
6870 ///   of a stack variable.
6871 static void
6872 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6873                      SourceLocation ReturnLoc) {
6874 
6875   const Expr *stackE = nullptr;
6876   SmallVector<const DeclRefExpr *, 8> refVars;
6877 
6878   // Perform checking for returned stack addresses, local blocks,
6879   // label addresses or references to temporaries.
6880   if (lhsType->isPointerType() ||
6881       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
6882     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
6883   } else if (lhsType->isReferenceType()) {
6884     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
6885   }
6886 
6887   if (!stackE)
6888     return; // Nothing suspicious was found.
6889 
6890   // Parameters are initalized in the calling scope, so taking the address
6891   // of a parameter reference doesn't need a warning.
6892   for (auto *DRE : refVars)
6893     if (isa<ParmVarDecl>(DRE->getDecl()))
6894       return;
6895 
6896   SourceLocation diagLoc;
6897   SourceRange diagRange;
6898   if (refVars.empty()) {
6899     diagLoc = stackE->getLocStart();
6900     diagRange = stackE->getSourceRange();
6901   } else {
6902     // We followed through a reference variable. 'stackE' contains the
6903     // problematic expression but we will warn at the return statement pointing
6904     // at the reference variable. We will later display the "trail" of
6905     // reference variables using notes.
6906     diagLoc = refVars[0]->getLocStart();
6907     diagRange = refVars[0]->getSourceRange();
6908   }
6909 
6910   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6911     // address of local var
6912     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
6913      << DR->getDecl()->getDeclName() << diagRange;
6914   } else if (isa<BlockExpr>(stackE)) { // local block.
6915     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6916   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
6917     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6918   } else { // local temporary.
6919     // If there is an LValue->RValue conversion, then the value of the
6920     // reference type is used, not the reference.
6921     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
6922       if (ICE->getCastKind() == CK_LValueToRValue) {
6923         return;
6924       }
6925     }
6926     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6927      << lhsType->isReferenceType() << diagRange;
6928   }
6929 
6930   // Display the "trail" of reference variables that we followed until we
6931   // found the problematic expression using notes.
6932   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
6933     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6934     // If this var binds to another reference var, show the range of the next
6935     // var, otherwise the var binds to the problematic expression, in which case
6936     // show the range of the expression.
6937     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6938                                     : stackE->getSourceRange();
6939     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6940         << VD->getDeclName() << range;
6941   }
6942 }
6943 
6944 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6945 ///  check if the expression in a return statement evaluates to an address
6946 ///  to a location on the stack, a local block, an address of a label, or a
6947 ///  reference to local temporary. The recursion is used to traverse the
6948 ///  AST of the return expression, with recursion backtracking when we
6949 ///  encounter a subexpression that (1) clearly does not lead to one of the
6950 ///  above problematic expressions (2) is something we cannot determine leads to
6951 ///  a problematic expression based on such local checking.
6952 ///
6953 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
6954 ///  the expression that they point to. Such variables are added to the
6955 ///  'refVars' vector so that we know what the reference variable "trail" was.
6956 ///
6957 ///  EvalAddr processes expressions that are pointers that are used as
6958 ///  references (and not L-values).  EvalVal handles all other values.
6959 ///  At the base case of the recursion is a check for the above problematic
6960 ///  expressions.
6961 ///
6962 ///  This implementation handles:
6963 ///
6964 ///   * pointer-to-pointer casts
6965 ///   * implicit conversions from array references to pointers
6966 ///   * taking the address of fields
6967 ///   * arbitrary interplay between "&" and "*" operators
6968 ///   * pointer arithmetic from an address of a stack variable
6969 ///   * taking the address of an array element where the array is on the stack
6970 static const Expr *EvalAddr(const Expr *E,
6971                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6972                             const Decl *ParentDecl) {
6973   if (E->isTypeDependent())
6974     return nullptr;
6975 
6976   // We should only be called for evaluating pointer expressions.
6977   assert((E->getType()->isAnyPointerType() ||
6978           E->getType()->isBlockPointerType() ||
6979           E->getType()->isObjCQualifiedIdType()) &&
6980          "EvalAddr only works on pointers");
6981 
6982   E = E->IgnoreParens();
6983 
6984   // Our "symbolic interpreter" is just a dispatch off the currently
6985   // viewed AST node.  We then recursively traverse the AST by calling
6986   // EvalAddr and EvalVal appropriately.
6987   switch (E->getStmtClass()) {
6988   case Stmt::DeclRefExprClass: {
6989     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6990 
6991     // If we leave the immediate function, the lifetime isn't about to end.
6992     if (DR->refersToEnclosingVariableOrCapture())
6993       return nullptr;
6994 
6995     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
6996       // If this is a reference variable, follow through to the expression that
6997       // it points to.
6998       if (V->hasLocalStorage() &&
6999           V->getType()->isReferenceType() && V->hasInit()) {
7000         // Add the reference variable to the "trail".
7001         refVars.push_back(DR);
7002         return EvalAddr(V->getInit(), refVars, ParentDecl);
7003       }
7004 
7005     return nullptr;
7006   }
7007 
7008   case Stmt::UnaryOperatorClass: {
7009     // The only unary operator that make sense to handle here
7010     // is AddrOf.  All others don't make sense as pointers.
7011     const UnaryOperator *U = cast<UnaryOperator>(E);
7012 
7013     if (U->getOpcode() == UO_AddrOf)
7014       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7015     return nullptr;
7016   }
7017 
7018   case Stmt::BinaryOperatorClass: {
7019     // Handle pointer arithmetic.  All other binary operators are not valid
7020     // in this context.
7021     const BinaryOperator *B = cast<BinaryOperator>(E);
7022     BinaryOperatorKind op = B->getOpcode();
7023 
7024     if (op != BO_Add && op != BO_Sub)
7025       return nullptr;
7026 
7027     const Expr *Base = B->getLHS();
7028 
7029     // Determine which argument is the real pointer base.  It could be
7030     // the RHS argument instead of the LHS.
7031     if (!Base->getType()->isPointerType())
7032       Base = B->getRHS();
7033 
7034     assert(Base->getType()->isPointerType());
7035     return EvalAddr(Base, refVars, ParentDecl);
7036   }
7037 
7038   // For conditional operators we need to see if either the LHS or RHS are
7039   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7040   case Stmt::ConditionalOperatorClass: {
7041     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7042 
7043     // Handle the GNU extension for missing LHS.
7044     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7045     if (const Expr *LHSExpr = C->getLHS()) {
7046       // In C++, we can have a throw-expression, which has 'void' type.
7047       if (!LHSExpr->getType()->isVoidType())
7048         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7049           return LHS;
7050     }
7051 
7052     // In C++, we can have a throw-expression, which has 'void' type.
7053     if (C->getRHS()->getType()->isVoidType())
7054       return nullptr;
7055 
7056     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7057   }
7058 
7059   case Stmt::BlockExprClass:
7060     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7061       return E; // local block.
7062     return nullptr;
7063 
7064   case Stmt::AddrLabelExprClass:
7065     return E; // address of label.
7066 
7067   case Stmt::ExprWithCleanupsClass:
7068     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7069                     ParentDecl);
7070 
7071   // For casts, we need to handle conversions from arrays to
7072   // pointer values, and pointer-to-pointer conversions.
7073   case Stmt::ImplicitCastExprClass:
7074   case Stmt::CStyleCastExprClass:
7075   case Stmt::CXXFunctionalCastExprClass:
7076   case Stmt::ObjCBridgedCastExprClass:
7077   case Stmt::CXXStaticCastExprClass:
7078   case Stmt::CXXDynamicCastExprClass:
7079   case Stmt::CXXConstCastExprClass:
7080   case Stmt::CXXReinterpretCastExprClass: {
7081     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7082     switch (cast<CastExpr>(E)->getCastKind()) {
7083     case CK_LValueToRValue:
7084     case CK_NoOp:
7085     case CK_BaseToDerived:
7086     case CK_DerivedToBase:
7087     case CK_UncheckedDerivedToBase:
7088     case CK_Dynamic:
7089     case CK_CPointerToObjCPointerCast:
7090     case CK_BlockPointerToObjCPointerCast:
7091     case CK_AnyPointerToBlockPointerCast:
7092       return EvalAddr(SubExpr, refVars, ParentDecl);
7093 
7094     case CK_ArrayToPointerDecay:
7095       return EvalVal(SubExpr, refVars, ParentDecl);
7096 
7097     case CK_BitCast:
7098       if (SubExpr->getType()->isAnyPointerType() ||
7099           SubExpr->getType()->isBlockPointerType() ||
7100           SubExpr->getType()->isObjCQualifiedIdType())
7101         return EvalAddr(SubExpr, refVars, ParentDecl);
7102       else
7103         return nullptr;
7104 
7105     default:
7106       return nullptr;
7107     }
7108   }
7109 
7110   case Stmt::MaterializeTemporaryExprClass:
7111     if (const Expr *Result =
7112             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7113                      refVars, ParentDecl))
7114       return Result;
7115     return E;
7116 
7117   // Everything else: we simply don't reason about them.
7118   default:
7119     return nullptr;
7120   }
7121 }
7122 
7123 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7124 ///   See the comments for EvalAddr for more details.
7125 static const Expr *EvalVal(const Expr *E,
7126                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7127                            const Decl *ParentDecl) {
7128   do {
7129     // We should only be called for evaluating non-pointer expressions, or
7130     // expressions with a pointer type that are not used as references but
7131     // instead
7132     // are l-values (e.g., DeclRefExpr with a pointer type).
7133 
7134     // Our "symbolic interpreter" is just a dispatch off the currently
7135     // viewed AST node.  We then recursively traverse the AST by calling
7136     // EvalAddr and EvalVal appropriately.
7137 
7138     E = E->IgnoreParens();
7139     switch (E->getStmtClass()) {
7140     case Stmt::ImplicitCastExprClass: {
7141       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7142       if (IE->getValueKind() == VK_LValue) {
7143         E = IE->getSubExpr();
7144         continue;
7145       }
7146       return nullptr;
7147     }
7148 
7149     case Stmt::ExprWithCleanupsClass:
7150       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7151                      ParentDecl);
7152 
7153     case Stmt::DeclRefExprClass: {
7154       // When we hit a DeclRefExpr we are looking at code that refers to a
7155       // variable's name. If it's not a reference variable we check if it has
7156       // local storage within the function, and if so, return the expression.
7157       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7158 
7159       // If we leave the immediate function, the lifetime isn't about to end.
7160       if (DR->refersToEnclosingVariableOrCapture())
7161         return nullptr;
7162 
7163       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7164         // Check if it refers to itself, e.g. "int& i = i;".
7165         if (V == ParentDecl)
7166           return DR;
7167 
7168         if (V->hasLocalStorage()) {
7169           if (!V->getType()->isReferenceType())
7170             return DR;
7171 
7172           // Reference variable, follow through to the expression that
7173           // it points to.
7174           if (V->hasInit()) {
7175             // Add the reference variable to the "trail".
7176             refVars.push_back(DR);
7177             return EvalVal(V->getInit(), refVars, V);
7178           }
7179         }
7180       }
7181 
7182       return nullptr;
7183     }
7184 
7185     case Stmt::UnaryOperatorClass: {
7186       // The only unary operator that make sense to handle here
7187       // is Deref.  All others don't resolve to a "name."  This includes
7188       // handling all sorts of rvalues passed to a unary operator.
7189       const UnaryOperator *U = cast<UnaryOperator>(E);
7190 
7191       if (U->getOpcode() == UO_Deref)
7192         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7193 
7194       return nullptr;
7195     }
7196 
7197     case Stmt::ArraySubscriptExprClass: {
7198       // Array subscripts are potential references to data on the stack.  We
7199       // retrieve the DeclRefExpr* for the array variable if it indeed
7200       // has local storage.
7201       const auto *ASE = cast<ArraySubscriptExpr>(E);
7202       if (ASE->isTypeDependent())
7203         return nullptr;
7204       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7205     }
7206 
7207     case Stmt::OMPArraySectionExprClass: {
7208       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7209                       ParentDecl);
7210     }
7211 
7212     case Stmt::ConditionalOperatorClass: {
7213       // For conditional operators we need to see if either the LHS or RHS are
7214       // non-NULL Expr's.  If one is non-NULL, we return it.
7215       const ConditionalOperator *C = cast<ConditionalOperator>(E);
7216 
7217       // Handle the GNU extension for missing LHS.
7218       if (const Expr *LHSExpr = C->getLHS()) {
7219         // In C++, we can have a throw-expression, which has 'void' type.
7220         if (!LHSExpr->getType()->isVoidType())
7221           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
7222             return LHS;
7223       }
7224 
7225       // In C++, we can have a throw-expression, which has 'void' type.
7226       if (C->getRHS()->getType()->isVoidType())
7227         return nullptr;
7228 
7229       return EvalVal(C->getRHS(), refVars, ParentDecl);
7230     }
7231 
7232     // Accesses to members are potential references to data on the stack.
7233     case Stmt::MemberExprClass: {
7234       const MemberExpr *M = cast<MemberExpr>(E);
7235 
7236       // Check for indirect access.  We only want direct field accesses.
7237       if (M->isArrow())
7238         return nullptr;
7239 
7240       // Check whether the member type is itself a reference, in which case
7241       // we're not going to refer to the member, but to what the member refers
7242       // to.
7243       if (M->getMemberDecl()->getType()->isReferenceType())
7244         return nullptr;
7245 
7246       return EvalVal(M->getBase(), refVars, ParentDecl);
7247     }
7248 
7249     case Stmt::MaterializeTemporaryExprClass:
7250       if (const Expr *Result =
7251               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7252                       refVars, ParentDecl))
7253         return Result;
7254       return E;
7255 
7256     default:
7257       // Check that we don't return or take the address of a reference to a
7258       // temporary. This is only useful in C++.
7259       if (!E->isTypeDependent() && E->isRValue())
7260         return E;
7261 
7262       // Everything else: we simply don't reason about them.
7263       return nullptr;
7264     }
7265   } while (true);
7266 }
7267 
7268 void
7269 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
7270                          SourceLocation ReturnLoc,
7271                          bool isObjCMethod,
7272                          const AttrVec *Attrs,
7273                          const FunctionDecl *FD) {
7274   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
7275 
7276   // Check if the return value is null but should not be.
7277   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7278        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
7279       CheckNonNullExpr(*this, RetValExp))
7280     Diag(ReturnLoc, diag::warn_null_ret)
7281       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
7282 
7283   // C++11 [basic.stc.dynamic.allocation]p4:
7284   //   If an allocation function declared with a non-throwing
7285   //   exception-specification fails to allocate storage, it shall return
7286   //   a null pointer. Any other allocation function that fails to allocate
7287   //   storage shall indicate failure only by throwing an exception [...]
7288   if (FD) {
7289     OverloadedOperatorKind Op = FD->getOverloadedOperator();
7290     if (Op == OO_New || Op == OO_Array_New) {
7291       const FunctionProtoType *Proto
7292         = FD->getType()->castAs<FunctionProtoType>();
7293       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
7294           CheckNonNullExpr(*this, RetValExp))
7295         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7296           << FD << getLangOpts().CPlusPlus11;
7297     }
7298   }
7299 }
7300 
7301 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
7302 
7303 /// Check for comparisons of floating point operands using != and ==.
7304 /// Issue a warning if these are no self-comparisons, as they are not likely
7305 /// to do what the programmer intended.
7306 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
7307   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
7308   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
7309 
7310   // Special case: check for x == x (which is OK).
7311   // Do not emit warnings for such cases.
7312   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7313     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7314       if (DRL->getDecl() == DRR->getDecl())
7315         return;
7316 
7317   // Special case: check for comparisons against literals that can be exactly
7318   //  represented by APFloat.  In such cases, do not emit a warning.  This
7319   //  is a heuristic: often comparison against such literals are used to
7320   //  detect if a value in a variable has not changed.  This clearly can
7321   //  lead to false negatives.
7322   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7323     if (FLL->isExact())
7324       return;
7325   } else
7326     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7327       if (FLR->isExact())
7328         return;
7329 
7330   // Check for comparisons with builtin types.
7331   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7332     if (CL->getBuiltinCallee())
7333       return;
7334 
7335   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7336     if (CR->getBuiltinCallee())
7337       return;
7338 
7339   // Emit the diagnostic.
7340   Diag(Loc, diag::warn_floatingpoint_eq)
7341     << LHS->getSourceRange() << RHS->getSourceRange();
7342 }
7343 
7344 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
7345 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
7346 
7347 namespace {
7348 
7349 /// Structure recording the 'active' range of an integer-valued
7350 /// expression.
7351 struct IntRange {
7352   /// The number of bits active in the int.
7353   unsigned Width;
7354 
7355   /// True if the int is known not to have negative values.
7356   bool NonNegative;
7357 
7358   IntRange(unsigned Width, bool NonNegative)
7359     : Width(Width), NonNegative(NonNegative)
7360   {}
7361 
7362   /// Returns the range of the bool type.
7363   static IntRange forBoolType() {
7364     return IntRange(1, true);
7365   }
7366 
7367   /// Returns the range of an opaque value of the given integral type.
7368   static IntRange forValueOfType(ASTContext &C, QualType T) {
7369     return forValueOfCanonicalType(C,
7370                           T->getCanonicalTypeInternal().getTypePtr());
7371   }
7372 
7373   /// Returns the range of an opaque value of a canonical integral type.
7374   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
7375     assert(T->isCanonicalUnqualified());
7376 
7377     if (const VectorType *VT = dyn_cast<VectorType>(T))
7378       T = VT->getElementType().getTypePtr();
7379     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7380       T = CT->getElementType().getTypePtr();
7381     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7382       T = AT->getValueType().getTypePtr();
7383 
7384     // For enum types, use the known bit width of the enumerators.
7385     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
7386       EnumDecl *Enum = ET->getDecl();
7387       if (!Enum->isCompleteDefinition())
7388         return IntRange(C.getIntWidth(QualType(T, 0)), false);
7389 
7390       unsigned NumPositive = Enum->getNumPositiveBits();
7391       unsigned NumNegative = Enum->getNumNegativeBits();
7392 
7393       if (NumNegative == 0)
7394         return IntRange(NumPositive, true/*NonNegative*/);
7395       else
7396         return IntRange(std::max(NumPositive + 1, NumNegative),
7397                         false/*NonNegative*/);
7398     }
7399 
7400     const BuiltinType *BT = cast<BuiltinType>(T);
7401     assert(BT->isInteger());
7402 
7403     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7404   }
7405 
7406   /// Returns the "target" range of a canonical integral type, i.e.
7407   /// the range of values expressible in the type.
7408   ///
7409   /// This matches forValueOfCanonicalType except that enums have the
7410   /// full range of their type, not the range of their enumerators.
7411   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
7412     assert(T->isCanonicalUnqualified());
7413 
7414     if (const VectorType *VT = dyn_cast<VectorType>(T))
7415       T = VT->getElementType().getTypePtr();
7416     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
7417       T = CT->getElementType().getTypePtr();
7418     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
7419       T = AT->getValueType().getTypePtr();
7420     if (const EnumType *ET = dyn_cast<EnumType>(T))
7421       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
7422 
7423     const BuiltinType *BT = cast<BuiltinType>(T);
7424     assert(BT->isInteger());
7425 
7426     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
7427   }
7428 
7429   /// Returns the supremum of two ranges: i.e. their conservative merge.
7430   static IntRange join(IntRange L, IntRange R) {
7431     return IntRange(std::max(L.Width, R.Width),
7432                     L.NonNegative && R.NonNegative);
7433   }
7434 
7435   /// Returns the infinum of two ranges: i.e. their aggressive merge.
7436   static IntRange meet(IntRange L, IntRange R) {
7437     return IntRange(std::min(L.Width, R.Width),
7438                     L.NonNegative || R.NonNegative);
7439   }
7440 };
7441 
7442 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
7443   if (value.isSigned() && value.isNegative())
7444     return IntRange(value.getMinSignedBits(), false);
7445 
7446   if (value.getBitWidth() > MaxWidth)
7447     value = value.trunc(MaxWidth);
7448 
7449   // isNonNegative() just checks the sign bit without considering
7450   // signedness.
7451   return IntRange(value.getActiveBits(), true);
7452 }
7453 
7454 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
7455                        unsigned MaxWidth) {
7456   if (result.isInt())
7457     return GetValueRange(C, result.getInt(), MaxWidth);
7458 
7459   if (result.isVector()) {
7460     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
7461     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
7462       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
7463       R = IntRange::join(R, El);
7464     }
7465     return R;
7466   }
7467 
7468   if (result.isComplexInt()) {
7469     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
7470     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
7471     return IntRange::join(R, I);
7472   }
7473 
7474   // This can happen with lossless casts to intptr_t of "based" lvalues.
7475   // Assume it might use arbitrary bits.
7476   // FIXME: The only reason we need to pass the type in here is to get
7477   // the sign right on this one case.  It would be nice if APValue
7478   // preserved this.
7479   assert(result.isLValue() || result.isAddrLabelDiff());
7480   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
7481 }
7482 
7483 QualType GetExprType(const Expr *E) {
7484   QualType Ty = E->getType();
7485   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
7486     Ty = AtomicRHS->getValueType();
7487   return Ty;
7488 }
7489 
7490 /// Pseudo-evaluate the given integer expression, estimating the
7491 /// range of values it might take.
7492 ///
7493 /// \param MaxWidth - the width to which the value will be truncated
7494 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
7495   E = E->IgnoreParens();
7496 
7497   // Try a full evaluation first.
7498   Expr::EvalResult result;
7499   if (E->EvaluateAsRValue(result, C))
7500     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
7501 
7502   // I think we only want to look through implicit casts here; if the
7503   // user has an explicit widening cast, we should treat the value as
7504   // being of the new, wider type.
7505   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
7506     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
7507       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
7508 
7509     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
7510 
7511     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
7512                          CE->getCastKind() == CK_BooleanToSignedIntegral;
7513 
7514     // Assume that non-integer casts can span the full range of the type.
7515     if (!isIntegerCast)
7516       return OutputTypeRange;
7517 
7518     IntRange SubRange
7519       = GetExprRange(C, CE->getSubExpr(),
7520                      std::min(MaxWidth, OutputTypeRange.Width));
7521 
7522     // Bail out if the subexpr's range is as wide as the cast type.
7523     if (SubRange.Width >= OutputTypeRange.Width)
7524       return OutputTypeRange;
7525 
7526     // Otherwise, we take the smaller width, and we're non-negative if
7527     // either the output type or the subexpr is.
7528     return IntRange(SubRange.Width,
7529                     SubRange.NonNegative || OutputTypeRange.NonNegative);
7530   }
7531 
7532   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
7533     // If we can fold the condition, just take that operand.
7534     bool CondResult;
7535     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
7536       return GetExprRange(C, CondResult ? CO->getTrueExpr()
7537                                         : CO->getFalseExpr(),
7538                           MaxWidth);
7539 
7540     // Otherwise, conservatively merge.
7541     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
7542     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
7543     return IntRange::join(L, R);
7544   }
7545 
7546   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
7547     switch (BO->getOpcode()) {
7548 
7549     // Boolean-valued operations are single-bit and positive.
7550     case BO_LAnd:
7551     case BO_LOr:
7552     case BO_LT:
7553     case BO_GT:
7554     case BO_LE:
7555     case BO_GE:
7556     case BO_EQ:
7557     case BO_NE:
7558       return IntRange::forBoolType();
7559 
7560     // The type of the assignments is the type of the LHS, so the RHS
7561     // is not necessarily the same type.
7562     case BO_MulAssign:
7563     case BO_DivAssign:
7564     case BO_RemAssign:
7565     case BO_AddAssign:
7566     case BO_SubAssign:
7567     case BO_XorAssign:
7568     case BO_OrAssign:
7569       // TODO: bitfields?
7570       return IntRange::forValueOfType(C, GetExprType(E));
7571 
7572     // Simple assignments just pass through the RHS, which will have
7573     // been coerced to the LHS type.
7574     case BO_Assign:
7575       // TODO: bitfields?
7576       return GetExprRange(C, BO->getRHS(), MaxWidth);
7577 
7578     // Operations with opaque sources are black-listed.
7579     case BO_PtrMemD:
7580     case BO_PtrMemI:
7581       return IntRange::forValueOfType(C, GetExprType(E));
7582 
7583     // Bitwise-and uses the *infinum* of the two source ranges.
7584     case BO_And:
7585     case BO_AndAssign:
7586       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
7587                             GetExprRange(C, BO->getRHS(), MaxWidth));
7588 
7589     // Left shift gets black-listed based on a judgement call.
7590     case BO_Shl:
7591       // ...except that we want to treat '1 << (blah)' as logically
7592       // positive.  It's an important idiom.
7593       if (IntegerLiteral *I
7594             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
7595         if (I->getValue() == 1) {
7596           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
7597           return IntRange(R.Width, /*NonNegative*/ true);
7598         }
7599       }
7600       // fallthrough
7601 
7602     case BO_ShlAssign:
7603       return IntRange::forValueOfType(C, GetExprType(E));
7604 
7605     // Right shift by a constant can narrow its left argument.
7606     case BO_Shr:
7607     case BO_ShrAssign: {
7608       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7609 
7610       // If the shift amount is a positive constant, drop the width by
7611       // that much.
7612       llvm::APSInt shift;
7613       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
7614           shift.isNonNegative()) {
7615         unsigned zext = shift.getZExtValue();
7616         if (zext >= L.Width)
7617           L.Width = (L.NonNegative ? 0 : 1);
7618         else
7619           L.Width -= zext;
7620       }
7621 
7622       return L;
7623     }
7624 
7625     // Comma acts as its right operand.
7626     case BO_Comma:
7627       return GetExprRange(C, BO->getRHS(), MaxWidth);
7628 
7629     // Black-list pointer subtractions.
7630     case BO_Sub:
7631       if (BO->getLHS()->getType()->isPointerType())
7632         return IntRange::forValueOfType(C, GetExprType(E));
7633       break;
7634 
7635     // The width of a division result is mostly determined by the size
7636     // of the LHS.
7637     case BO_Div: {
7638       // Don't 'pre-truncate' the operands.
7639       unsigned opWidth = C.getIntWidth(GetExprType(E));
7640       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7641 
7642       // If the divisor is constant, use that.
7643       llvm::APSInt divisor;
7644       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
7645         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
7646         if (log2 >= L.Width)
7647           L.Width = (L.NonNegative ? 0 : 1);
7648         else
7649           L.Width = std::min(L.Width - log2, MaxWidth);
7650         return L;
7651       }
7652 
7653       // Otherwise, just use the LHS's width.
7654       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7655       return IntRange(L.Width, L.NonNegative && R.NonNegative);
7656     }
7657 
7658     // The result of a remainder can't be larger than the result of
7659     // either side.
7660     case BO_Rem: {
7661       // Don't 'pre-truncate' the operands.
7662       unsigned opWidth = C.getIntWidth(GetExprType(E));
7663       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
7664       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
7665 
7666       IntRange meet = IntRange::meet(L, R);
7667       meet.Width = std::min(meet.Width, MaxWidth);
7668       return meet;
7669     }
7670 
7671     // The default behavior is okay for these.
7672     case BO_Mul:
7673     case BO_Add:
7674     case BO_Xor:
7675     case BO_Or:
7676       break;
7677     }
7678 
7679     // The default case is to treat the operation as if it were closed
7680     // on the narrowest type that encompasses both operands.
7681     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
7682     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
7683     return IntRange::join(L, R);
7684   }
7685 
7686   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
7687     switch (UO->getOpcode()) {
7688     // Boolean-valued operations are white-listed.
7689     case UO_LNot:
7690       return IntRange::forBoolType();
7691 
7692     // Operations with opaque sources are black-listed.
7693     case UO_Deref:
7694     case UO_AddrOf: // should be impossible
7695       return IntRange::forValueOfType(C, GetExprType(E));
7696 
7697     default:
7698       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
7699     }
7700   }
7701 
7702   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
7703     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
7704 
7705   if (const auto *BitField = E->getSourceBitField())
7706     return IntRange(BitField->getBitWidthValue(C),
7707                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
7708 
7709   return IntRange::forValueOfType(C, GetExprType(E));
7710 }
7711 
7712 IntRange GetExprRange(ASTContext &C, const Expr *E) {
7713   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
7714 }
7715 
7716 /// Checks whether the given value, which currently has the given
7717 /// source semantics, has the same value when coerced through the
7718 /// target semantics.
7719 bool IsSameFloatAfterCast(const llvm::APFloat &value,
7720                           const llvm::fltSemantics &Src,
7721                           const llvm::fltSemantics &Tgt) {
7722   llvm::APFloat truncated = value;
7723 
7724   bool ignored;
7725   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
7726   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
7727 
7728   return truncated.bitwiseIsEqual(value);
7729 }
7730 
7731 /// Checks whether the given value, which currently has the given
7732 /// source semantics, has the same value when coerced through the
7733 /// target semantics.
7734 ///
7735 /// The value might be a vector of floats (or a complex number).
7736 bool IsSameFloatAfterCast(const APValue &value,
7737                           const llvm::fltSemantics &Src,
7738                           const llvm::fltSemantics &Tgt) {
7739   if (value.isFloat())
7740     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
7741 
7742   if (value.isVector()) {
7743     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
7744       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
7745         return false;
7746     return true;
7747   }
7748 
7749   assert(value.isComplexFloat());
7750   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
7751           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
7752 }
7753 
7754 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
7755 
7756 bool IsZero(Sema &S, Expr *E) {
7757   // Suppress cases where we are comparing against an enum constant.
7758   if (const DeclRefExpr *DR =
7759       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
7760     if (isa<EnumConstantDecl>(DR->getDecl()))
7761       return false;
7762 
7763   // Suppress cases where the '0' value is expanded from a macro.
7764   if (E->getLocStart().isMacroID())
7765     return false;
7766 
7767   llvm::APSInt Value;
7768   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
7769 }
7770 
7771 bool HasEnumType(Expr *E) {
7772   // Strip off implicit integral promotions.
7773   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7774     if (ICE->getCastKind() != CK_IntegralCast &&
7775         ICE->getCastKind() != CK_NoOp)
7776       break;
7777     E = ICE->getSubExpr();
7778   }
7779 
7780   return E->getType()->isEnumeralType();
7781 }
7782 
7783 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
7784   // Disable warning in template instantiations.
7785   if (!S.ActiveTemplateInstantiations.empty())
7786     return;
7787 
7788   BinaryOperatorKind op = E->getOpcode();
7789   if (E->isValueDependent())
7790     return;
7791 
7792   if (op == BO_LT && IsZero(S, E->getRHS())) {
7793     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7794       << "< 0" << "false" << HasEnumType(E->getLHS())
7795       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7796   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
7797     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
7798       << ">= 0" << "true" << HasEnumType(E->getLHS())
7799       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7800   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
7801     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7802       << "0 >" << "false" << HasEnumType(E->getRHS())
7803       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7804   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
7805     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
7806       << "0 <=" << "true" << HasEnumType(E->getRHS())
7807       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
7808   }
7809 }
7810 
7811 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
7812                                   Expr *Other, const llvm::APSInt &Value,
7813                                   bool RhsConstant) {
7814   // Disable warning in template instantiations.
7815   if (!S.ActiveTemplateInstantiations.empty())
7816     return;
7817 
7818   // TODO: Investigate using GetExprRange() to get tighter bounds
7819   // on the bit ranges.
7820   QualType OtherT = Other->getType();
7821   if (const auto *AT = OtherT->getAs<AtomicType>())
7822     OtherT = AT->getValueType();
7823   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
7824   unsigned OtherWidth = OtherRange.Width;
7825 
7826   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
7827 
7828   // 0 values are handled later by CheckTrivialUnsignedComparison().
7829   if ((Value == 0) && (!OtherIsBooleanType))
7830     return;
7831 
7832   BinaryOperatorKind op = E->getOpcode();
7833   bool IsTrue = true;
7834 
7835   // Used for diagnostic printout.
7836   enum {
7837     LiteralConstant = 0,
7838     CXXBoolLiteralTrue,
7839     CXXBoolLiteralFalse
7840   } LiteralOrBoolConstant = LiteralConstant;
7841 
7842   if (!OtherIsBooleanType) {
7843     QualType ConstantT = Constant->getType();
7844     QualType CommonT = E->getLHS()->getType();
7845 
7846     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7847       return;
7848     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7849            "comparison with non-integer type");
7850 
7851     bool ConstantSigned = ConstantT->isSignedIntegerType();
7852     bool CommonSigned = CommonT->isSignedIntegerType();
7853 
7854     bool EqualityOnly = false;
7855 
7856     if (CommonSigned) {
7857       // The common type is signed, therefore no signed to unsigned conversion.
7858       if (!OtherRange.NonNegative) {
7859         // Check that the constant is representable in type OtherT.
7860         if (ConstantSigned) {
7861           if (OtherWidth >= Value.getMinSignedBits())
7862             return;
7863         } else { // !ConstantSigned
7864           if (OtherWidth >= Value.getActiveBits() + 1)
7865             return;
7866         }
7867       } else { // !OtherSigned
7868                // Check that the constant is representable in type OtherT.
7869         // Negative values are out of range.
7870         if (ConstantSigned) {
7871           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7872             return;
7873         } else { // !ConstantSigned
7874           if (OtherWidth >= Value.getActiveBits())
7875             return;
7876         }
7877       }
7878     } else { // !CommonSigned
7879       if (OtherRange.NonNegative) {
7880         if (OtherWidth >= Value.getActiveBits())
7881           return;
7882       } else { // OtherSigned
7883         assert(!ConstantSigned &&
7884                "Two signed types converted to unsigned types.");
7885         // Check to see if the constant is representable in OtherT.
7886         if (OtherWidth > Value.getActiveBits())
7887           return;
7888         // Check to see if the constant is equivalent to a negative value
7889         // cast to CommonT.
7890         if (S.Context.getIntWidth(ConstantT) ==
7891                 S.Context.getIntWidth(CommonT) &&
7892             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7893           return;
7894         // The constant value rests between values that OtherT can represent
7895         // after conversion.  Relational comparison still works, but equality
7896         // comparisons will be tautological.
7897         EqualityOnly = true;
7898       }
7899     }
7900 
7901     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7902 
7903     if (op == BO_EQ || op == BO_NE) {
7904       IsTrue = op == BO_NE;
7905     } else if (EqualityOnly) {
7906       return;
7907     } else if (RhsConstant) {
7908       if (op == BO_GT || op == BO_GE)
7909         IsTrue = !PositiveConstant;
7910       else // op == BO_LT || op == BO_LE
7911         IsTrue = PositiveConstant;
7912     } else {
7913       if (op == BO_LT || op == BO_LE)
7914         IsTrue = !PositiveConstant;
7915       else // op == BO_GT || op == BO_GE
7916         IsTrue = PositiveConstant;
7917     }
7918   } else {
7919     // Other isKnownToHaveBooleanValue
7920     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7921     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7922     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7923 
7924     static const struct LinkedConditions {
7925       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7926       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7927       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7928       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7929       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7930       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7931 
7932     } TruthTable = {
7933         // Constant on LHS.              | Constant on RHS.              |
7934         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
7935         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7936         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7937         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7938         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7939         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7940         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7941       };
7942 
7943     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7944 
7945     enum ConstantValue ConstVal = Zero;
7946     if (Value.isUnsigned() || Value.isNonNegative()) {
7947       if (Value == 0) {
7948         LiteralOrBoolConstant =
7949             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7950         ConstVal = Zero;
7951       } else if (Value == 1) {
7952         LiteralOrBoolConstant =
7953             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7954         ConstVal = One;
7955       } else {
7956         LiteralOrBoolConstant = LiteralConstant;
7957         ConstVal = GT_One;
7958       }
7959     } else {
7960       ConstVal = LT_Zero;
7961     }
7962 
7963     CompareBoolWithConstantResult CmpRes;
7964 
7965     switch (op) {
7966     case BO_LT:
7967       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7968       break;
7969     case BO_GT:
7970       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7971       break;
7972     case BO_LE:
7973       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7974       break;
7975     case BO_GE:
7976       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7977       break;
7978     case BO_EQ:
7979       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7980       break;
7981     case BO_NE:
7982       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7983       break;
7984     default:
7985       CmpRes = Unkwn;
7986       break;
7987     }
7988 
7989     if (CmpRes == AFals) {
7990       IsTrue = false;
7991     } else if (CmpRes == ATrue) {
7992       IsTrue = true;
7993     } else {
7994       return;
7995     }
7996   }
7997 
7998   // If this is a comparison to an enum constant, include that
7999   // constant in the diagnostic.
8000   const EnumConstantDecl *ED = nullptr;
8001   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8002     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8003 
8004   SmallString<64> PrettySourceValue;
8005   llvm::raw_svector_ostream OS(PrettySourceValue);
8006   if (ED)
8007     OS << '\'' << *ED << "' (" << Value << ")";
8008   else
8009     OS << Value;
8010 
8011   S.DiagRuntimeBehavior(
8012     E->getOperatorLoc(), E,
8013     S.PDiag(diag::warn_out_of_range_compare)
8014         << OS.str() << LiteralOrBoolConstant
8015         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8016         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8017 }
8018 
8019 /// Analyze the operands of the given comparison.  Implements the
8020 /// fallback case from AnalyzeComparison.
8021 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8022   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8023   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8024 }
8025 
8026 /// \brief Implements -Wsign-compare.
8027 ///
8028 /// \param E the binary operator to check for warnings
8029 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8030   // The type the comparison is being performed in.
8031   QualType T = E->getLHS()->getType();
8032 
8033   // Only analyze comparison operators where both sides have been converted to
8034   // the same type.
8035   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8036     return AnalyzeImpConvsInComparison(S, E);
8037 
8038   // Don't analyze value-dependent comparisons directly.
8039   if (E->isValueDependent())
8040     return AnalyzeImpConvsInComparison(S, E);
8041 
8042   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8043   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8044 
8045   bool IsComparisonConstant = false;
8046 
8047   // Check whether an integer constant comparison results in a value
8048   // of 'true' or 'false'.
8049   if (T->isIntegralType(S.Context)) {
8050     llvm::APSInt RHSValue;
8051     bool IsRHSIntegralLiteral =
8052       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8053     llvm::APSInt LHSValue;
8054     bool IsLHSIntegralLiteral =
8055       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8056     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8057         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8058     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8059       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8060     else
8061       IsComparisonConstant =
8062         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8063   } else if (!T->hasUnsignedIntegerRepresentation())
8064       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8065 
8066   // We don't do anything special if this isn't an unsigned integral
8067   // comparison:  we're only interested in integral comparisons, and
8068   // signed comparisons only happen in cases we don't care to warn about.
8069   //
8070   // We also don't care about value-dependent expressions or expressions
8071   // whose result is a constant.
8072   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
8073     return AnalyzeImpConvsInComparison(S, E);
8074 
8075   // Check to see if one of the (unmodified) operands is of different
8076   // signedness.
8077   Expr *signedOperand, *unsignedOperand;
8078   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8079     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8080            "unsigned comparison between two signed integer expressions?");
8081     signedOperand = LHS;
8082     unsignedOperand = RHS;
8083   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8084     signedOperand = RHS;
8085     unsignedOperand = LHS;
8086   } else {
8087     CheckTrivialUnsignedComparison(S, E);
8088     return AnalyzeImpConvsInComparison(S, E);
8089   }
8090 
8091   // Otherwise, calculate the effective range of the signed operand.
8092   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8093 
8094   // Go ahead and analyze implicit conversions in the operands.  Note
8095   // that we skip the implicit conversions on both sides.
8096   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8097   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8098 
8099   // If the signed range is non-negative, -Wsign-compare won't fire,
8100   // but we should still check for comparisons which are always true
8101   // or false.
8102   if (signedRange.NonNegative)
8103     return CheckTrivialUnsignedComparison(S, E);
8104 
8105   // For (in)equality comparisons, if the unsigned operand is a
8106   // constant which cannot collide with a overflowed signed operand,
8107   // then reinterpreting the signed operand as unsigned will not
8108   // change the result of the comparison.
8109   if (E->isEqualityOp()) {
8110     unsigned comparisonWidth = S.Context.getIntWidth(T);
8111     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8112 
8113     // We should never be unable to prove that the unsigned operand is
8114     // non-negative.
8115     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8116 
8117     if (unsignedRange.Width < comparisonWidth)
8118       return;
8119   }
8120 
8121   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8122     S.PDiag(diag::warn_mixed_sign_comparison)
8123       << LHS->getType() << RHS->getType()
8124       << LHS->getSourceRange() << RHS->getSourceRange());
8125 }
8126 
8127 /// Analyzes an attempt to assign the given value to a bitfield.
8128 ///
8129 /// Returns true if there was something fishy about the attempt.
8130 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8131                                SourceLocation InitLoc) {
8132   assert(Bitfield->isBitField());
8133   if (Bitfield->isInvalidDecl())
8134     return false;
8135 
8136   // White-list bool bitfields.
8137   if (Bitfield->getType()->isBooleanType())
8138     return false;
8139 
8140   // Ignore value- or type-dependent expressions.
8141   if (Bitfield->getBitWidth()->isValueDependent() ||
8142       Bitfield->getBitWidth()->isTypeDependent() ||
8143       Init->isValueDependent() ||
8144       Init->isTypeDependent())
8145     return false;
8146 
8147   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8148 
8149   llvm::APSInt Value;
8150   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
8151     return false;
8152 
8153   unsigned OriginalWidth = Value.getBitWidth();
8154   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8155 
8156   if (!Value.isSigned() || Value.isNegative())
8157     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8158       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8159         OriginalWidth = Value.getMinSignedBits();
8160 
8161   if (OriginalWidth <= FieldWidth)
8162     return false;
8163 
8164   // Compute the value which the bitfield will contain.
8165   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8166   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
8167 
8168   // Check whether the stored value is equal to the original value.
8169   TruncatedValue = TruncatedValue.extend(OriginalWidth);
8170   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8171     return false;
8172 
8173   // Special-case bitfields of width 1: booleans are naturally 0/1, and
8174   // therefore don't strictly fit into a signed bitfield of width 1.
8175   if (FieldWidth == 1 && Value == 1)
8176     return false;
8177 
8178   std::string PrettyValue = Value.toString(10);
8179   std::string PrettyTrunc = TruncatedValue.toString(10);
8180 
8181   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8182     << PrettyValue << PrettyTrunc << OriginalInit->getType()
8183     << Init->getSourceRange();
8184 
8185   return true;
8186 }
8187 
8188 /// Analyze the given simple or compound assignment for warning-worthy
8189 /// operations.
8190 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
8191   // Just recurse on the LHS.
8192   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8193 
8194   // We want to recurse on the RHS as normal unless we're assigning to
8195   // a bitfield.
8196   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
8197     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
8198                                   E->getOperatorLoc())) {
8199       // Recurse, ignoring any implicit conversions on the RHS.
8200       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
8201                                         E->getOperatorLoc());
8202     }
8203   }
8204 
8205   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8206 }
8207 
8208 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8209 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
8210                      SourceLocation CContext, unsigned diag,
8211                      bool pruneControlFlow = false) {
8212   if (pruneControlFlow) {
8213     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8214                           S.PDiag(diag)
8215                             << SourceType << T << E->getSourceRange()
8216                             << SourceRange(CContext));
8217     return;
8218   }
8219   S.Diag(E->getExprLoc(), diag)
8220     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
8221 }
8222 
8223 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
8224 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
8225                      unsigned diag, bool pruneControlFlow = false) {
8226   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
8227 }
8228 
8229 
8230 /// Diagnose an implicit cast from a floating point value to an integer value.
8231 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
8232 
8233                              SourceLocation CContext) {
8234   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
8235   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
8236 
8237   Expr *InnerE = E->IgnoreParenImpCasts();
8238   // We also want to warn on, e.g., "int i = -1.234"
8239   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
8240     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8241       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
8242 
8243   const bool IsLiteral =
8244       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
8245 
8246   llvm::APFloat Value(0.0);
8247   bool IsConstant =
8248     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
8249   if (!IsConstant) {
8250     return DiagnoseImpCast(S, E, T, CContext,
8251                            diag::warn_impcast_float_integer, PruneWarnings);
8252   }
8253 
8254   bool isExact = false;
8255 
8256   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
8257                             T->hasUnsignedIntegerRepresentation());
8258   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8259                              &isExact) == llvm::APFloat::opOK &&
8260       isExact) {
8261     if (IsLiteral) return;
8262     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8263                            PruneWarnings);
8264   }
8265 
8266   unsigned DiagID = 0;
8267   if (IsLiteral) {
8268     // Warn on floating point literal to integer.
8269     DiagID = diag::warn_impcast_literal_float_to_integer;
8270   } else if (IntegerValue == 0) {
8271     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
8272       return DiagnoseImpCast(S, E, T, CContext,
8273                              diag::warn_impcast_float_integer, PruneWarnings);
8274     }
8275     // Warn on non-zero to zero conversion.
8276     DiagID = diag::warn_impcast_float_to_integer_zero;
8277   } else {
8278     if (IntegerValue.isUnsigned()) {
8279       if (!IntegerValue.isMaxValue()) {
8280         return DiagnoseImpCast(S, E, T, CContext,
8281                                diag::warn_impcast_float_integer, PruneWarnings);
8282       }
8283     } else {  // IntegerValue.isSigned()
8284       if (!IntegerValue.isMaxSignedValue() &&
8285           !IntegerValue.isMinSignedValue()) {
8286         return DiagnoseImpCast(S, E, T, CContext,
8287                                diag::warn_impcast_float_integer, PruneWarnings);
8288       }
8289     }
8290     // Warn on evaluatable floating point expression to integer conversion.
8291     DiagID = diag::warn_impcast_float_to_integer;
8292   }
8293 
8294   // FIXME: Force the precision of the source value down so we don't print
8295   // digits which are usually useless (we don't really care here if we
8296   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
8297   // would automatically print the shortest representation, but it's a bit
8298   // tricky to implement.
8299   SmallString<16> PrettySourceValue;
8300   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
8301   precision = (precision * 59 + 195) / 196;
8302   Value.toString(PrettySourceValue, precision);
8303 
8304   SmallString<16> PrettyTargetValue;
8305   if (IsBool)
8306     PrettyTargetValue = Value.isZero() ? "false" : "true";
8307   else
8308     IntegerValue.toString(PrettyTargetValue);
8309 
8310   if (PruneWarnings) {
8311     S.DiagRuntimeBehavior(E->getExprLoc(), E,
8312                           S.PDiag(DiagID)
8313                               << E->getType() << T.getUnqualifiedType()
8314                               << PrettySourceValue << PrettyTargetValue
8315                               << E->getSourceRange() << SourceRange(CContext));
8316   } else {
8317     S.Diag(E->getExprLoc(), DiagID)
8318         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
8319         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
8320   }
8321 }
8322 
8323 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
8324   if (!Range.Width) return "0";
8325 
8326   llvm::APSInt ValueInRange = Value;
8327   ValueInRange.setIsSigned(!Range.NonNegative);
8328   ValueInRange = ValueInRange.trunc(Range.Width);
8329   return ValueInRange.toString(10);
8330 }
8331 
8332 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
8333   if (!isa<ImplicitCastExpr>(Ex))
8334     return false;
8335 
8336   Expr *InnerE = Ex->IgnoreParenImpCasts();
8337   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
8338   const Type *Source =
8339     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
8340   if (Target->isDependentType())
8341     return false;
8342 
8343   const BuiltinType *FloatCandidateBT =
8344     dyn_cast<BuiltinType>(ToBool ? Source : Target);
8345   const Type *BoolCandidateType = ToBool ? Target : Source;
8346 
8347   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
8348           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
8349 }
8350 
8351 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
8352                                       SourceLocation CC) {
8353   unsigned NumArgs = TheCall->getNumArgs();
8354   for (unsigned i = 0; i < NumArgs; ++i) {
8355     Expr *CurrA = TheCall->getArg(i);
8356     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
8357       continue;
8358 
8359     bool IsSwapped = ((i > 0) &&
8360         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
8361     IsSwapped |= ((i < (NumArgs - 1)) &&
8362         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
8363     if (IsSwapped) {
8364       // Warn on this floating-point to bool conversion.
8365       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
8366                       CurrA->getType(), CC,
8367                       diag::warn_impcast_floating_point_to_bool);
8368     }
8369   }
8370 }
8371 
8372 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
8373   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
8374                         E->getExprLoc()))
8375     return;
8376 
8377   // Don't warn on functions which have return type nullptr_t.
8378   if (isa<CallExpr>(E))
8379     return;
8380 
8381   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
8382   const Expr::NullPointerConstantKind NullKind =
8383       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
8384   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
8385     return;
8386 
8387   // Return if target type is a safe conversion.
8388   if (T->isAnyPointerType() || T->isBlockPointerType() ||
8389       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
8390     return;
8391 
8392   SourceLocation Loc = E->getSourceRange().getBegin();
8393 
8394   // Venture through the macro stacks to get to the source of macro arguments.
8395   // The new location is a better location than the complete location that was
8396   // passed in.
8397   while (S.SourceMgr.isMacroArgExpansion(Loc))
8398     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
8399 
8400   while (S.SourceMgr.isMacroArgExpansion(CC))
8401     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
8402 
8403   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
8404   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
8405     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
8406         Loc, S.SourceMgr, S.getLangOpts());
8407     if (MacroName == "NULL")
8408       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
8409   }
8410 
8411   // Only warn if the null and context location are in the same macro expansion.
8412   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
8413     return;
8414 
8415   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
8416       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
8417       << FixItHint::CreateReplacement(Loc,
8418                                       S.getFixItZeroLiteralForType(T, Loc));
8419 }
8420 
8421 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8422                            ObjCArrayLiteral *ArrayLiteral);
8423 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8424                                 ObjCDictionaryLiteral *DictionaryLiteral);
8425 
8426 /// Check a single element within a collection literal against the
8427 /// target element type.
8428 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
8429                                        Expr *Element, unsigned ElementKind) {
8430   // Skip a bitcast to 'id' or qualified 'id'.
8431   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
8432     if (ICE->getCastKind() == CK_BitCast &&
8433         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
8434       Element = ICE->getSubExpr();
8435   }
8436 
8437   QualType ElementType = Element->getType();
8438   ExprResult ElementResult(Element);
8439   if (ElementType->getAs<ObjCObjectPointerType>() &&
8440       S.CheckSingleAssignmentConstraints(TargetElementType,
8441                                          ElementResult,
8442                                          false, false)
8443         != Sema::Compatible) {
8444     S.Diag(Element->getLocStart(),
8445            diag::warn_objc_collection_literal_element)
8446       << ElementType << ElementKind << TargetElementType
8447       << Element->getSourceRange();
8448   }
8449 
8450   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
8451     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
8452   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
8453     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
8454 }
8455 
8456 /// Check an Objective-C array literal being converted to the given
8457 /// target type.
8458 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
8459                            ObjCArrayLiteral *ArrayLiteral) {
8460   if (!S.NSArrayDecl)
8461     return;
8462 
8463   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8464   if (!TargetObjCPtr)
8465     return;
8466 
8467   if (TargetObjCPtr->isUnspecialized() ||
8468       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8469         != S.NSArrayDecl->getCanonicalDecl())
8470     return;
8471 
8472   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8473   if (TypeArgs.size() != 1)
8474     return;
8475 
8476   QualType TargetElementType = TypeArgs[0];
8477   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
8478     checkObjCCollectionLiteralElement(S, TargetElementType,
8479                                       ArrayLiteral->getElement(I),
8480                                       0);
8481   }
8482 }
8483 
8484 /// Check an Objective-C dictionary literal being converted to the given
8485 /// target type.
8486 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
8487                                 ObjCDictionaryLiteral *DictionaryLiteral) {
8488   if (!S.NSDictionaryDecl)
8489     return;
8490 
8491   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
8492   if (!TargetObjCPtr)
8493     return;
8494 
8495   if (TargetObjCPtr->isUnspecialized() ||
8496       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
8497         != S.NSDictionaryDecl->getCanonicalDecl())
8498     return;
8499 
8500   auto TypeArgs = TargetObjCPtr->getTypeArgs();
8501   if (TypeArgs.size() != 2)
8502     return;
8503 
8504   QualType TargetKeyType = TypeArgs[0];
8505   QualType TargetObjectType = TypeArgs[1];
8506   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
8507     auto Element = DictionaryLiteral->getKeyValueElement(I);
8508     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
8509     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
8510   }
8511 }
8512 
8513 // Helper function to filter out cases for constant width constant conversion.
8514 // Don't warn on char array initialization or for non-decimal values.
8515 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
8516                                    SourceLocation CC) {
8517   // If initializing from a constant, and the constant starts with '0',
8518   // then it is a binary, octal, or hexadecimal.  Allow these constants
8519   // to fill all the bits, even if there is a sign change.
8520   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
8521     const char FirstLiteralCharacter =
8522         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
8523     if (FirstLiteralCharacter == '0')
8524       return false;
8525   }
8526 
8527   // If the CC location points to a '{', and the type is char, then assume
8528   // assume it is an array initialization.
8529   if (CC.isValid() && T->isCharType()) {
8530     const char FirstContextCharacter =
8531         S.getSourceManager().getCharacterData(CC)[0];
8532     if (FirstContextCharacter == '{')
8533       return false;
8534   }
8535 
8536   return true;
8537 }
8538 
8539 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
8540                              SourceLocation CC, bool *ICContext = nullptr) {
8541   if (E->isTypeDependent() || E->isValueDependent()) return;
8542 
8543   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
8544   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
8545   if (Source == Target) return;
8546   if (Target->isDependentType()) return;
8547 
8548   // If the conversion context location is invalid don't complain. We also
8549   // don't want to emit a warning if the issue occurs from the expansion of
8550   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
8551   // delay this check as long as possible. Once we detect we are in that
8552   // scenario, we just return.
8553   if (CC.isInvalid())
8554     return;
8555 
8556   // Diagnose implicit casts to bool.
8557   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
8558     if (isa<StringLiteral>(E))
8559       // Warn on string literal to bool.  Checks for string literals in logical
8560       // and expressions, for instance, assert(0 && "error here"), are
8561       // prevented by a check in AnalyzeImplicitConversions().
8562       return DiagnoseImpCast(S, E, T, CC,
8563                              diag::warn_impcast_string_literal_to_bool);
8564     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
8565         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
8566       // This covers the literal expressions that evaluate to Objective-C
8567       // objects.
8568       return DiagnoseImpCast(S, E, T, CC,
8569                              diag::warn_impcast_objective_c_literal_to_bool);
8570     }
8571     if (Source->isPointerType() || Source->canDecayToPointerType()) {
8572       // Warn on pointer to bool conversion that is always true.
8573       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
8574                                      SourceRange(CC));
8575     }
8576   }
8577 
8578   // Check implicit casts from Objective-C collection literals to specialized
8579   // collection types, e.g., NSArray<NSString *> *.
8580   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
8581     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
8582   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
8583     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
8584 
8585   // Strip vector types.
8586   if (isa<VectorType>(Source)) {
8587     if (!isa<VectorType>(Target)) {
8588       if (S.SourceMgr.isInSystemMacro(CC))
8589         return;
8590       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
8591     }
8592 
8593     // If the vector cast is cast between two vectors of the same size, it is
8594     // a bitcast, not a conversion.
8595     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
8596       return;
8597 
8598     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
8599     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
8600   }
8601   if (auto VecTy = dyn_cast<VectorType>(Target))
8602     Target = VecTy->getElementType().getTypePtr();
8603 
8604   // Strip complex types.
8605   if (isa<ComplexType>(Source)) {
8606     if (!isa<ComplexType>(Target)) {
8607       if (S.SourceMgr.isInSystemMacro(CC))
8608         return;
8609 
8610       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
8611     }
8612 
8613     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
8614     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
8615   }
8616 
8617   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
8618   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
8619 
8620   // If the source is floating point...
8621   if (SourceBT && SourceBT->isFloatingPoint()) {
8622     // ...and the target is floating point...
8623     if (TargetBT && TargetBT->isFloatingPoint()) {
8624       // ...then warn if we're dropping FP rank.
8625 
8626       // Builtin FP kinds are ordered by increasing FP rank.
8627       if (SourceBT->getKind() > TargetBT->getKind()) {
8628         // Don't warn about float constants that are precisely
8629         // representable in the target type.
8630         Expr::EvalResult result;
8631         if (E->EvaluateAsRValue(result, S.Context)) {
8632           // Value might be a float, a float vector, or a float complex.
8633           if (IsSameFloatAfterCast(result.Val,
8634                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
8635                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
8636             return;
8637         }
8638 
8639         if (S.SourceMgr.isInSystemMacro(CC))
8640           return;
8641 
8642         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
8643       }
8644       // ... or possibly if we're increasing rank, too
8645       else if (TargetBT->getKind() > SourceBT->getKind()) {
8646         if (S.SourceMgr.isInSystemMacro(CC))
8647           return;
8648 
8649         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
8650       }
8651       return;
8652     }
8653 
8654     // If the target is integral, always warn.
8655     if (TargetBT && TargetBT->isInteger()) {
8656       if (S.SourceMgr.isInSystemMacro(CC))
8657         return;
8658 
8659       DiagnoseFloatingImpCast(S, E, T, CC);
8660     }
8661 
8662     // Detect the case where a call result is converted from floating-point to
8663     // to bool, and the final argument to the call is converted from bool, to
8664     // discover this typo:
8665     //
8666     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
8667     //
8668     // FIXME: This is an incredibly special case; is there some more general
8669     // way to detect this class of misplaced-parentheses bug?
8670     if (Target->isBooleanType() && isa<CallExpr>(E)) {
8671       // Check last argument of function call to see if it is an
8672       // implicit cast from a type matching the type the result
8673       // is being cast to.
8674       CallExpr *CEx = cast<CallExpr>(E);
8675       if (unsigned NumArgs = CEx->getNumArgs()) {
8676         Expr *LastA = CEx->getArg(NumArgs - 1);
8677         Expr *InnerE = LastA->IgnoreParenImpCasts();
8678         if (isa<ImplicitCastExpr>(LastA) &&
8679             InnerE->getType()->isBooleanType()) {
8680           // Warn on this floating-point to bool conversion
8681           DiagnoseImpCast(S, E, T, CC,
8682                           diag::warn_impcast_floating_point_to_bool);
8683         }
8684       }
8685     }
8686     return;
8687   }
8688 
8689   DiagnoseNullConversion(S, E, T, CC);
8690 
8691   S.DiscardMisalignedMemberAddress(Target, E);
8692 
8693   if (!Source->isIntegerType() || !Target->isIntegerType())
8694     return;
8695 
8696   // TODO: remove this early return once the false positives for constant->bool
8697   // in templates, macros, etc, are reduced or removed.
8698   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
8699     return;
8700 
8701   IntRange SourceRange = GetExprRange(S.Context, E);
8702   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
8703 
8704   if (SourceRange.Width > TargetRange.Width) {
8705     // If the source is a constant, use a default-on diagnostic.
8706     // TODO: this should happen for bitfield stores, too.
8707     llvm::APSInt Value(32);
8708     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
8709       if (S.SourceMgr.isInSystemMacro(CC))
8710         return;
8711 
8712       std::string PrettySourceValue = Value.toString(10);
8713       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8714 
8715       S.DiagRuntimeBehavior(E->getExprLoc(), E,
8716         S.PDiag(diag::warn_impcast_integer_precision_constant)
8717             << PrettySourceValue << PrettyTargetValue
8718             << E->getType() << T << E->getSourceRange()
8719             << clang::SourceRange(CC));
8720       return;
8721     }
8722 
8723     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
8724     if (S.SourceMgr.isInSystemMacro(CC))
8725       return;
8726 
8727     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
8728       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
8729                              /* pruneControlFlow */ true);
8730     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
8731   }
8732 
8733   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
8734       SourceRange.NonNegative && Source->isSignedIntegerType()) {
8735     // Warn when doing a signed to signed conversion, warn if the positive
8736     // source value is exactly the width of the target type, which will
8737     // cause a negative value to be stored.
8738 
8739     llvm::APSInt Value;
8740     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
8741         !S.SourceMgr.isInSystemMacro(CC)) {
8742       if (isSameWidthConstantConversion(S, E, T, CC)) {
8743         std::string PrettySourceValue = Value.toString(10);
8744         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
8745 
8746         S.DiagRuntimeBehavior(
8747             E->getExprLoc(), E,
8748             S.PDiag(diag::warn_impcast_integer_precision_constant)
8749                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
8750                 << E->getSourceRange() << clang::SourceRange(CC));
8751         return;
8752       }
8753     }
8754 
8755     // Fall through for non-constants to give a sign conversion warning.
8756   }
8757 
8758   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
8759       (!TargetRange.NonNegative && SourceRange.NonNegative &&
8760        SourceRange.Width == TargetRange.Width)) {
8761     if (S.SourceMgr.isInSystemMacro(CC))
8762       return;
8763 
8764     unsigned DiagID = diag::warn_impcast_integer_sign;
8765 
8766     // Traditionally, gcc has warned about this under -Wsign-compare.
8767     // We also want to warn about it in -Wconversion.
8768     // So if -Wconversion is off, use a completely identical diagnostic
8769     // in the sign-compare group.
8770     // The conditional-checking code will
8771     if (ICContext) {
8772       DiagID = diag::warn_impcast_integer_sign_conditional;
8773       *ICContext = true;
8774     }
8775 
8776     return DiagnoseImpCast(S, E, T, CC, DiagID);
8777   }
8778 
8779   // Diagnose conversions between different enumeration types.
8780   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
8781   // type, to give us better diagnostics.
8782   QualType SourceType = E->getType();
8783   if (!S.getLangOpts().CPlusPlus) {
8784     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8785       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
8786         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
8787         SourceType = S.Context.getTypeDeclType(Enum);
8788         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
8789       }
8790   }
8791 
8792   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
8793     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
8794       if (SourceEnum->getDecl()->hasNameForLinkage() &&
8795           TargetEnum->getDecl()->hasNameForLinkage() &&
8796           SourceEnum != TargetEnum) {
8797         if (S.SourceMgr.isInSystemMacro(CC))
8798           return;
8799 
8800         return DiagnoseImpCast(S, E, SourceType, T, CC,
8801                                diag::warn_impcast_different_enum_types);
8802       }
8803 }
8804 
8805 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8806                               SourceLocation CC, QualType T);
8807 
8808 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
8809                              SourceLocation CC, bool &ICContext) {
8810   E = E->IgnoreParenImpCasts();
8811 
8812   if (isa<ConditionalOperator>(E))
8813     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
8814 
8815   AnalyzeImplicitConversions(S, E, CC);
8816   if (E->getType() != T)
8817     return CheckImplicitConversion(S, E, T, CC, &ICContext);
8818 }
8819 
8820 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
8821                               SourceLocation CC, QualType T) {
8822   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
8823 
8824   bool Suspicious = false;
8825   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
8826   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
8827 
8828   // If -Wconversion would have warned about either of the candidates
8829   // for a signedness conversion to the context type...
8830   if (!Suspicious) return;
8831 
8832   // ...but it's currently ignored...
8833   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
8834     return;
8835 
8836   // ...then check whether it would have warned about either of the
8837   // candidates for a signedness conversion to the condition type.
8838   if (E->getType() == T) return;
8839 
8840   Suspicious = false;
8841   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8842                           E->getType(), CC, &Suspicious);
8843   if (!Suspicious)
8844     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
8845                             E->getType(), CC, &Suspicious);
8846 }
8847 
8848 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8849 /// Input argument E is a logical expression.
8850 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
8851   if (S.getLangOpts().Bool)
8852     return;
8853   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8854 }
8855 
8856 /// AnalyzeImplicitConversions - Find and report any interesting
8857 /// implicit conversions in the given expression.  There are a couple
8858 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
8859 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
8860   QualType T = OrigE->getType();
8861   Expr *E = OrigE->IgnoreParenImpCasts();
8862 
8863   if (E->isTypeDependent() || E->isValueDependent())
8864     return;
8865 
8866   // For conditional operators, we analyze the arguments as if they
8867   // were being fed directly into the output.
8868   if (isa<ConditionalOperator>(E)) {
8869     ConditionalOperator *CO = cast<ConditionalOperator>(E);
8870     CheckConditionalOperator(S, CO, CC, T);
8871     return;
8872   }
8873 
8874   // Check implicit argument conversions for function calls.
8875   if (CallExpr *Call = dyn_cast<CallExpr>(E))
8876     CheckImplicitArgumentConversions(S, Call, CC);
8877 
8878   // Go ahead and check any implicit conversions we might have skipped.
8879   // The non-canonical typecheck is just an optimization;
8880   // CheckImplicitConversion will filter out dead implicit conversions.
8881   if (E->getType() != T)
8882     CheckImplicitConversion(S, E, T, CC);
8883 
8884   // Now continue drilling into this expression.
8885 
8886   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8887     // The bound subexpressions in a PseudoObjectExpr are not reachable
8888     // as transitive children.
8889     // FIXME: Use a more uniform representation for this.
8890     for (auto *SE : POE->semantics())
8891       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8892         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8893   }
8894 
8895   // Skip past explicit casts.
8896   if (isa<ExplicitCastExpr>(E)) {
8897     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
8898     return AnalyzeImplicitConversions(S, E, CC);
8899   }
8900 
8901   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8902     // Do a somewhat different check with comparison operators.
8903     if (BO->isComparisonOp())
8904       return AnalyzeComparison(S, BO);
8905 
8906     // And with simple assignments.
8907     if (BO->getOpcode() == BO_Assign)
8908       return AnalyzeAssignment(S, BO);
8909   }
8910 
8911   // These break the otherwise-useful invariant below.  Fortunately,
8912   // we don't really need to recurse into them, because any internal
8913   // expressions should have been analyzed already when they were
8914   // built into statements.
8915   if (isa<StmtExpr>(E)) return;
8916 
8917   // Don't descend into unevaluated contexts.
8918   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
8919 
8920   // Now just recurse over the expression's children.
8921   CC = E->getExprLoc();
8922   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
8923   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
8924   for (Stmt *SubStmt : E->children()) {
8925     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8926     if (!ChildExpr)
8927       continue;
8928 
8929     if (IsLogicalAndOperator &&
8930         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
8931       // Ignore checking string literals that are in logical and operators.
8932       // This is a common pattern for asserts.
8933       continue;
8934     AnalyzeImplicitConversions(S, ChildExpr, CC);
8935   }
8936 
8937   if (BO && BO->isLogicalOp()) {
8938     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8939     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8940       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8941 
8942     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8943     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8944       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8945   }
8946 
8947   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8948     if (U->getOpcode() == UO_LNot)
8949       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8950 }
8951 
8952 } // end anonymous namespace
8953 
8954 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
8955                                             unsigned Start, unsigned End) {
8956   bool IllegalParams = false;
8957   for (unsigned I = Start; I <= End; ++I) {
8958     QualType Ty = TheCall->getArg(I)->getType();
8959     // Taking into account implicit conversions,
8960     // allow any integer within 32 bits range
8961     if (!Ty->isIntegerType() ||
8962         S.Context.getTypeSizeInChars(Ty).getQuantity() > 4) {
8963       S.Diag(TheCall->getArg(I)->getLocStart(),
8964              diag::err_opencl_enqueue_kernel_invalid_local_size_type);
8965       IllegalParams = true;
8966     }
8967     // Potentially emit standard warnings for implicit conversions if enabled
8968     // using -Wconversion.
8969     CheckImplicitConversion(S, TheCall->getArg(I), S.Context.UnsignedIntTy,
8970                             TheCall->getArg(I)->getLocStart());
8971   }
8972   return IllegalParams;
8973 }
8974 
8975 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8976 // Returns true when emitting a warning about taking the address of a reference.
8977 static bool CheckForReference(Sema &SemaRef, const Expr *E,
8978                               const PartialDiagnostic &PD) {
8979   E = E->IgnoreParenImpCasts();
8980 
8981   const FunctionDecl *FD = nullptr;
8982 
8983   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8984     if (!DRE->getDecl()->getType()->isReferenceType())
8985       return false;
8986   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8987     if (!M->getMemberDecl()->getType()->isReferenceType())
8988       return false;
8989   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8990     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
8991       return false;
8992     FD = Call->getDirectCallee();
8993   } else {
8994     return false;
8995   }
8996 
8997   SemaRef.Diag(E->getExprLoc(), PD);
8998 
8999   // If possible, point to location of function.
9000   if (FD) {
9001     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9002   }
9003 
9004   return true;
9005 }
9006 
9007 // Returns true if the SourceLocation is expanded from any macro body.
9008 // Returns false if the SourceLocation is invalid, is from not in a macro
9009 // expansion, or is from expanded from a top-level macro argument.
9010 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9011   if (Loc.isInvalid())
9012     return false;
9013 
9014   while (Loc.isMacroID()) {
9015     if (SM.isMacroBodyExpansion(Loc))
9016       return true;
9017     Loc = SM.getImmediateMacroCallerLoc(Loc);
9018   }
9019 
9020   return false;
9021 }
9022 
9023 /// \brief Diagnose pointers that are always non-null.
9024 /// \param E the expression containing the pointer
9025 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9026 /// compared to a null pointer
9027 /// \param IsEqual True when the comparison is equal to a null pointer
9028 /// \param Range Extra SourceRange to highlight in the diagnostic
9029 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9030                                         Expr::NullPointerConstantKind NullKind,
9031                                         bool IsEqual, SourceRange Range) {
9032   if (!E)
9033     return;
9034 
9035   // Don't warn inside macros.
9036   if (E->getExprLoc().isMacroID()) {
9037     const SourceManager &SM = getSourceManager();
9038     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9039         IsInAnyMacroBody(SM, Range.getBegin()))
9040       return;
9041   }
9042   E = E->IgnoreImpCasts();
9043 
9044   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9045 
9046   if (isa<CXXThisExpr>(E)) {
9047     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9048                                 : diag::warn_this_bool_conversion;
9049     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9050     return;
9051   }
9052 
9053   bool IsAddressOf = false;
9054 
9055   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9056     if (UO->getOpcode() != UO_AddrOf)
9057       return;
9058     IsAddressOf = true;
9059     E = UO->getSubExpr();
9060   }
9061 
9062   if (IsAddressOf) {
9063     unsigned DiagID = IsCompare
9064                           ? diag::warn_address_of_reference_null_compare
9065                           : diag::warn_address_of_reference_bool_conversion;
9066     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9067                                          << IsEqual;
9068     if (CheckForReference(*this, E, PD)) {
9069       return;
9070     }
9071   }
9072 
9073   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9074     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9075     std::string Str;
9076     llvm::raw_string_ostream S(Str);
9077     E->printPretty(S, nullptr, getPrintingPolicy());
9078     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9079                                 : diag::warn_cast_nonnull_to_bool;
9080     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9081       << E->getSourceRange() << Range << IsEqual;
9082     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9083   };
9084 
9085   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9086   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9087     if (auto *Callee = Call->getDirectCallee()) {
9088       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9089         ComplainAboutNonnullParamOrCall(A);
9090         return;
9091       }
9092     }
9093   }
9094 
9095   // Expect to find a single Decl.  Skip anything more complicated.
9096   ValueDecl *D = nullptr;
9097   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9098     D = R->getDecl();
9099   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9100     D = M->getMemberDecl();
9101   }
9102 
9103   // Weak Decls can be null.
9104   if (!D || D->isWeak())
9105     return;
9106 
9107   // Check for parameter decl with nonnull attribute
9108   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9109     if (getCurFunction() &&
9110         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9111       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9112         ComplainAboutNonnullParamOrCall(A);
9113         return;
9114       }
9115 
9116       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9117         auto ParamIter = llvm::find(FD->parameters(), PV);
9118         assert(ParamIter != FD->param_end());
9119         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
9120 
9121         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
9122           if (!NonNull->args_size()) {
9123               ComplainAboutNonnullParamOrCall(NonNull);
9124               return;
9125           }
9126 
9127           for (unsigned ArgNo : NonNull->args()) {
9128             if (ArgNo == ParamNo) {
9129               ComplainAboutNonnullParamOrCall(NonNull);
9130               return;
9131             }
9132           }
9133         }
9134       }
9135     }
9136   }
9137 
9138   QualType T = D->getType();
9139   const bool IsArray = T->isArrayType();
9140   const bool IsFunction = T->isFunctionType();
9141 
9142   // Address of function is used to silence the function warning.
9143   if (IsAddressOf && IsFunction) {
9144     return;
9145   }
9146 
9147   // Found nothing.
9148   if (!IsAddressOf && !IsFunction && !IsArray)
9149     return;
9150 
9151   // Pretty print the expression for the diagnostic.
9152   std::string Str;
9153   llvm::raw_string_ostream S(Str);
9154   E->printPretty(S, nullptr, getPrintingPolicy());
9155 
9156   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9157                               : diag::warn_impcast_pointer_to_bool;
9158   enum {
9159     AddressOf,
9160     FunctionPointer,
9161     ArrayPointer
9162   } DiagType;
9163   if (IsAddressOf)
9164     DiagType = AddressOf;
9165   else if (IsFunction)
9166     DiagType = FunctionPointer;
9167   else if (IsArray)
9168     DiagType = ArrayPointer;
9169   else
9170     llvm_unreachable("Could not determine diagnostic.");
9171   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
9172                                 << Range << IsEqual;
9173 
9174   if (!IsFunction)
9175     return;
9176 
9177   // Suggest '&' to silence the function warning.
9178   Diag(E->getExprLoc(), diag::note_function_warning_silence)
9179       << FixItHint::CreateInsertion(E->getLocStart(), "&");
9180 
9181   // Check to see if '()' fixit should be emitted.
9182   QualType ReturnType;
9183   UnresolvedSet<4> NonTemplateOverloads;
9184   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9185   if (ReturnType.isNull())
9186     return;
9187 
9188   if (IsCompare) {
9189     // There are two cases here.  If there is null constant, the only suggest
9190     // for a pointer return type.  If the null is 0, then suggest if the return
9191     // type is a pointer or an integer type.
9192     if (!ReturnType->isPointerType()) {
9193       if (NullKind == Expr::NPCK_ZeroExpression ||
9194           NullKind == Expr::NPCK_ZeroLiteral) {
9195         if (!ReturnType->isIntegerType())
9196           return;
9197       } else {
9198         return;
9199       }
9200     }
9201   } else { // !IsCompare
9202     // For function to bool, only suggest if the function pointer has bool
9203     // return type.
9204     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9205       return;
9206   }
9207   Diag(E->getExprLoc(), diag::note_function_to_function_call)
9208       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
9209 }
9210 
9211 /// Diagnoses "dangerous" implicit conversions within the given
9212 /// expression (which is a full expression).  Implements -Wconversion
9213 /// and -Wsign-compare.
9214 ///
9215 /// \param CC the "context" location of the implicit conversion, i.e.
9216 ///   the most location of the syntactic entity requiring the implicit
9217 ///   conversion
9218 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
9219   // Don't diagnose in unevaluated contexts.
9220   if (isUnevaluatedContext())
9221     return;
9222 
9223   // Don't diagnose for value- or type-dependent expressions.
9224   if (E->isTypeDependent() || E->isValueDependent())
9225     return;
9226 
9227   // Check for array bounds violations in cases where the check isn't triggered
9228   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
9229   // ArraySubscriptExpr is on the RHS of a variable initialization.
9230   CheckArrayAccess(E);
9231 
9232   // This is not the right CC for (e.g.) a variable initialization.
9233   AnalyzeImplicitConversions(*this, E, CC);
9234 }
9235 
9236 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9237 /// Input argument E is a logical expression.
9238 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
9239   ::CheckBoolLikeConversion(*this, E, CC);
9240 }
9241 
9242 /// Diagnose when expression is an integer constant expression and its evaluation
9243 /// results in integer overflow
9244 void Sema::CheckForIntOverflow (Expr *E) {
9245   // Use a work list to deal with nested struct initializers.
9246   SmallVector<Expr *, 2> Exprs(1, E);
9247 
9248   do {
9249     Expr *E = Exprs.pop_back_val();
9250 
9251     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
9252       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
9253       continue;
9254     }
9255 
9256     if (auto InitList = dyn_cast<InitListExpr>(E))
9257       Exprs.append(InitList->inits().begin(), InitList->inits().end());
9258   } while (!Exprs.empty());
9259 }
9260 
9261 namespace {
9262 /// \brief Visitor for expressions which looks for unsequenced operations on the
9263 /// same object.
9264 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
9265   typedef EvaluatedExprVisitor<SequenceChecker> Base;
9266 
9267   /// \brief A tree of sequenced regions within an expression. Two regions are
9268   /// unsequenced if one is an ancestor or a descendent of the other. When we
9269   /// finish processing an expression with sequencing, such as a comma
9270   /// expression, we fold its tree nodes into its parent, since they are
9271   /// unsequenced with respect to nodes we will visit later.
9272   class SequenceTree {
9273     struct Value {
9274       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
9275       unsigned Parent : 31;
9276       unsigned Merged : 1;
9277     };
9278     SmallVector<Value, 8> Values;
9279 
9280   public:
9281     /// \brief A region within an expression which may be sequenced with respect
9282     /// to some other region.
9283     class Seq {
9284       explicit Seq(unsigned N) : Index(N) {}
9285       unsigned Index;
9286       friend class SequenceTree;
9287     public:
9288       Seq() : Index(0) {}
9289     };
9290 
9291     SequenceTree() { Values.push_back(Value(0)); }
9292     Seq root() const { return Seq(0); }
9293 
9294     /// \brief Create a new sequence of operations, which is an unsequenced
9295     /// subset of \p Parent. This sequence of operations is sequenced with
9296     /// respect to other children of \p Parent.
9297     Seq allocate(Seq Parent) {
9298       Values.push_back(Value(Parent.Index));
9299       return Seq(Values.size() - 1);
9300     }
9301 
9302     /// \brief Merge a sequence of operations into its parent.
9303     void merge(Seq S) {
9304       Values[S.Index].Merged = true;
9305     }
9306 
9307     /// \brief Determine whether two operations are unsequenced. This operation
9308     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
9309     /// should have been merged into its parent as appropriate.
9310     bool isUnsequenced(Seq Cur, Seq Old) {
9311       unsigned C = representative(Cur.Index);
9312       unsigned Target = representative(Old.Index);
9313       while (C >= Target) {
9314         if (C == Target)
9315           return true;
9316         C = Values[C].Parent;
9317       }
9318       return false;
9319     }
9320 
9321   private:
9322     /// \brief Pick a representative for a sequence.
9323     unsigned representative(unsigned K) {
9324       if (Values[K].Merged)
9325         // Perform path compression as we go.
9326         return Values[K].Parent = representative(Values[K].Parent);
9327       return K;
9328     }
9329   };
9330 
9331   /// An object for which we can track unsequenced uses.
9332   typedef NamedDecl *Object;
9333 
9334   /// Different flavors of object usage which we track. We only track the
9335   /// least-sequenced usage of each kind.
9336   enum UsageKind {
9337     /// A read of an object. Multiple unsequenced reads are OK.
9338     UK_Use,
9339     /// A modification of an object which is sequenced before the value
9340     /// computation of the expression, such as ++n in C++.
9341     UK_ModAsValue,
9342     /// A modification of an object which is not sequenced before the value
9343     /// computation of the expression, such as n++.
9344     UK_ModAsSideEffect,
9345 
9346     UK_Count = UK_ModAsSideEffect + 1
9347   };
9348 
9349   struct Usage {
9350     Usage() : Use(nullptr), Seq() {}
9351     Expr *Use;
9352     SequenceTree::Seq Seq;
9353   };
9354 
9355   struct UsageInfo {
9356     UsageInfo() : Diagnosed(false) {}
9357     Usage Uses[UK_Count];
9358     /// Have we issued a diagnostic for this variable already?
9359     bool Diagnosed;
9360   };
9361   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
9362 
9363   Sema &SemaRef;
9364   /// Sequenced regions within the expression.
9365   SequenceTree Tree;
9366   /// Declaration modifications and references which we have seen.
9367   UsageInfoMap UsageMap;
9368   /// The region we are currently within.
9369   SequenceTree::Seq Region;
9370   /// Filled in with declarations which were modified as a side-effect
9371   /// (that is, post-increment operations).
9372   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
9373   /// Expressions to check later. We defer checking these to reduce
9374   /// stack usage.
9375   SmallVectorImpl<Expr *> &WorkList;
9376 
9377   /// RAII object wrapping the visitation of a sequenced subexpression of an
9378   /// expression. At the end of this process, the side-effects of the evaluation
9379   /// become sequenced with respect to the value computation of the result, so
9380   /// we downgrade any UK_ModAsSideEffect within the evaluation to
9381   /// UK_ModAsValue.
9382   struct SequencedSubexpression {
9383     SequencedSubexpression(SequenceChecker &Self)
9384       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
9385       Self.ModAsSideEffect = &ModAsSideEffect;
9386     }
9387     ~SequencedSubexpression() {
9388       for (auto &M : llvm::reverse(ModAsSideEffect)) {
9389         UsageInfo &U = Self.UsageMap[M.first];
9390         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
9391         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
9392         SideEffectUsage = M.second;
9393       }
9394       Self.ModAsSideEffect = OldModAsSideEffect;
9395     }
9396 
9397     SequenceChecker &Self;
9398     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
9399     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
9400   };
9401 
9402   /// RAII object wrapping the visitation of a subexpression which we might
9403   /// choose to evaluate as a constant. If any subexpression is evaluated and
9404   /// found to be non-constant, this allows us to suppress the evaluation of
9405   /// the outer expression.
9406   class EvaluationTracker {
9407   public:
9408     EvaluationTracker(SequenceChecker &Self)
9409         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
9410       Self.EvalTracker = this;
9411     }
9412     ~EvaluationTracker() {
9413       Self.EvalTracker = Prev;
9414       if (Prev)
9415         Prev->EvalOK &= EvalOK;
9416     }
9417 
9418     bool evaluate(const Expr *E, bool &Result) {
9419       if (!EvalOK || E->isValueDependent())
9420         return false;
9421       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
9422       return EvalOK;
9423     }
9424 
9425   private:
9426     SequenceChecker &Self;
9427     EvaluationTracker *Prev;
9428     bool EvalOK;
9429   } *EvalTracker;
9430 
9431   /// \brief Find the object which is produced by the specified expression,
9432   /// if any.
9433   Object getObject(Expr *E, bool Mod) const {
9434     E = E->IgnoreParenCasts();
9435     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9436       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
9437         return getObject(UO->getSubExpr(), Mod);
9438     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9439       if (BO->getOpcode() == BO_Comma)
9440         return getObject(BO->getRHS(), Mod);
9441       if (Mod && BO->isAssignmentOp())
9442         return getObject(BO->getLHS(), Mod);
9443     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9444       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
9445       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
9446         return ME->getMemberDecl();
9447     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9448       // FIXME: If this is a reference, map through to its value.
9449       return DRE->getDecl();
9450     return nullptr;
9451   }
9452 
9453   /// \brief Note that an object was modified or used by an expression.
9454   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
9455     Usage &U = UI.Uses[UK];
9456     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
9457       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
9458         ModAsSideEffect->push_back(std::make_pair(O, U));
9459       U.Use = Ref;
9460       U.Seq = Region;
9461     }
9462   }
9463   /// \brief Check whether a modification or use conflicts with a prior usage.
9464   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
9465                   bool IsModMod) {
9466     if (UI.Diagnosed)
9467       return;
9468 
9469     const Usage &U = UI.Uses[OtherKind];
9470     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
9471       return;
9472 
9473     Expr *Mod = U.Use;
9474     Expr *ModOrUse = Ref;
9475     if (OtherKind == UK_Use)
9476       std::swap(Mod, ModOrUse);
9477 
9478     SemaRef.Diag(Mod->getExprLoc(),
9479                  IsModMod ? diag::warn_unsequenced_mod_mod
9480                           : diag::warn_unsequenced_mod_use)
9481       << O << SourceRange(ModOrUse->getExprLoc());
9482     UI.Diagnosed = true;
9483   }
9484 
9485   void notePreUse(Object O, Expr *Use) {
9486     UsageInfo &U = UsageMap[O];
9487     // Uses conflict with other modifications.
9488     checkUsage(O, U, Use, UK_ModAsValue, false);
9489   }
9490   void notePostUse(Object O, Expr *Use) {
9491     UsageInfo &U = UsageMap[O];
9492     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
9493     addUsage(U, O, Use, UK_Use);
9494   }
9495 
9496   void notePreMod(Object O, Expr *Mod) {
9497     UsageInfo &U = UsageMap[O];
9498     // Modifications conflict with other modifications and with uses.
9499     checkUsage(O, U, Mod, UK_ModAsValue, true);
9500     checkUsage(O, U, Mod, UK_Use, false);
9501   }
9502   void notePostMod(Object O, Expr *Use, UsageKind UK) {
9503     UsageInfo &U = UsageMap[O];
9504     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
9505     addUsage(U, O, Use, UK);
9506   }
9507 
9508 public:
9509   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
9510       : Base(S.Context), SemaRef(S), Region(Tree.root()),
9511         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
9512     Visit(E);
9513   }
9514 
9515   void VisitStmt(Stmt *S) {
9516     // Skip all statements which aren't expressions for now.
9517   }
9518 
9519   void VisitExpr(Expr *E) {
9520     // By default, just recurse to evaluated subexpressions.
9521     Base::VisitStmt(E);
9522   }
9523 
9524   void VisitCastExpr(CastExpr *E) {
9525     Object O = Object();
9526     if (E->getCastKind() == CK_LValueToRValue)
9527       O = getObject(E->getSubExpr(), false);
9528 
9529     if (O)
9530       notePreUse(O, E);
9531     VisitExpr(E);
9532     if (O)
9533       notePostUse(O, E);
9534   }
9535 
9536   void VisitBinComma(BinaryOperator *BO) {
9537     // C++11 [expr.comma]p1:
9538     //   Every value computation and side effect associated with the left
9539     //   expression is sequenced before every value computation and side
9540     //   effect associated with the right expression.
9541     SequenceTree::Seq LHS = Tree.allocate(Region);
9542     SequenceTree::Seq RHS = Tree.allocate(Region);
9543     SequenceTree::Seq OldRegion = Region;
9544 
9545     {
9546       SequencedSubexpression SeqLHS(*this);
9547       Region = LHS;
9548       Visit(BO->getLHS());
9549     }
9550 
9551     Region = RHS;
9552     Visit(BO->getRHS());
9553 
9554     Region = OldRegion;
9555 
9556     // Forget that LHS and RHS are sequenced. They are both unsequenced
9557     // with respect to other stuff.
9558     Tree.merge(LHS);
9559     Tree.merge(RHS);
9560   }
9561 
9562   void VisitBinAssign(BinaryOperator *BO) {
9563     // The modification is sequenced after the value computation of the LHS
9564     // and RHS, so check it before inspecting the operands and update the
9565     // map afterwards.
9566     Object O = getObject(BO->getLHS(), true);
9567     if (!O)
9568       return VisitExpr(BO);
9569 
9570     notePreMod(O, BO);
9571 
9572     // C++11 [expr.ass]p7:
9573     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
9574     //   only once.
9575     //
9576     // Therefore, for a compound assignment operator, O is considered used
9577     // everywhere except within the evaluation of E1 itself.
9578     if (isa<CompoundAssignOperator>(BO))
9579       notePreUse(O, BO);
9580 
9581     Visit(BO->getLHS());
9582 
9583     if (isa<CompoundAssignOperator>(BO))
9584       notePostUse(O, BO);
9585 
9586     Visit(BO->getRHS());
9587 
9588     // C++11 [expr.ass]p1:
9589     //   the assignment is sequenced [...] before the value computation of the
9590     //   assignment expression.
9591     // C11 6.5.16/3 has no such rule.
9592     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9593                                                        : UK_ModAsSideEffect);
9594   }
9595 
9596   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
9597     VisitBinAssign(CAO);
9598   }
9599 
9600   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9601   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
9602   void VisitUnaryPreIncDec(UnaryOperator *UO) {
9603     Object O = getObject(UO->getSubExpr(), true);
9604     if (!O)
9605       return VisitExpr(UO);
9606 
9607     notePreMod(O, UO);
9608     Visit(UO->getSubExpr());
9609     // C++11 [expr.pre.incr]p1:
9610     //   the expression ++x is equivalent to x+=1
9611     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
9612                                                        : UK_ModAsSideEffect);
9613   }
9614 
9615   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9616   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
9617   void VisitUnaryPostIncDec(UnaryOperator *UO) {
9618     Object O = getObject(UO->getSubExpr(), true);
9619     if (!O)
9620       return VisitExpr(UO);
9621 
9622     notePreMod(O, UO);
9623     Visit(UO->getSubExpr());
9624     notePostMod(O, UO, UK_ModAsSideEffect);
9625   }
9626 
9627   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
9628   void VisitBinLOr(BinaryOperator *BO) {
9629     // The side-effects of the LHS of an '&&' are sequenced before the
9630     // value computation of the RHS, and hence before the value computation
9631     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
9632     // as if they were unconditionally sequenced.
9633     EvaluationTracker Eval(*this);
9634     {
9635       SequencedSubexpression Sequenced(*this);
9636       Visit(BO->getLHS());
9637     }
9638 
9639     bool Result;
9640     if (Eval.evaluate(BO->getLHS(), Result)) {
9641       if (!Result)
9642         Visit(BO->getRHS());
9643     } else {
9644       // Check for unsequenced operations in the RHS, treating it as an
9645       // entirely separate evaluation.
9646       //
9647       // FIXME: If there are operations in the RHS which are unsequenced
9648       // with respect to operations outside the RHS, and those operations
9649       // are unconditionally evaluated, diagnose them.
9650       WorkList.push_back(BO->getRHS());
9651     }
9652   }
9653   void VisitBinLAnd(BinaryOperator *BO) {
9654     EvaluationTracker Eval(*this);
9655     {
9656       SequencedSubexpression Sequenced(*this);
9657       Visit(BO->getLHS());
9658     }
9659 
9660     bool Result;
9661     if (Eval.evaluate(BO->getLHS(), Result)) {
9662       if (Result)
9663         Visit(BO->getRHS());
9664     } else {
9665       WorkList.push_back(BO->getRHS());
9666     }
9667   }
9668 
9669   // Only visit the condition, unless we can be sure which subexpression will
9670   // be chosen.
9671   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
9672     EvaluationTracker Eval(*this);
9673     {
9674       SequencedSubexpression Sequenced(*this);
9675       Visit(CO->getCond());
9676     }
9677 
9678     bool Result;
9679     if (Eval.evaluate(CO->getCond(), Result))
9680       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
9681     else {
9682       WorkList.push_back(CO->getTrueExpr());
9683       WorkList.push_back(CO->getFalseExpr());
9684     }
9685   }
9686 
9687   void VisitCallExpr(CallExpr *CE) {
9688     // C++11 [intro.execution]p15:
9689     //   When calling a function [...], every value computation and side effect
9690     //   associated with any argument expression, or with the postfix expression
9691     //   designating the called function, is sequenced before execution of every
9692     //   expression or statement in the body of the function [and thus before
9693     //   the value computation of its result].
9694     SequencedSubexpression Sequenced(*this);
9695     Base::VisitCallExpr(CE);
9696 
9697     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
9698   }
9699 
9700   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
9701     // This is a call, so all subexpressions are sequenced before the result.
9702     SequencedSubexpression Sequenced(*this);
9703 
9704     if (!CCE->isListInitialization())
9705       return VisitExpr(CCE);
9706 
9707     // In C++11, list initializations are sequenced.
9708     SmallVector<SequenceTree::Seq, 32> Elts;
9709     SequenceTree::Seq Parent = Region;
9710     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
9711                                         E = CCE->arg_end();
9712          I != E; ++I) {
9713       Region = Tree.allocate(Parent);
9714       Elts.push_back(Region);
9715       Visit(*I);
9716     }
9717 
9718     // Forget that the initializers are sequenced.
9719     Region = Parent;
9720     for (unsigned I = 0; I < Elts.size(); ++I)
9721       Tree.merge(Elts[I]);
9722   }
9723 
9724   void VisitInitListExpr(InitListExpr *ILE) {
9725     if (!SemaRef.getLangOpts().CPlusPlus11)
9726       return VisitExpr(ILE);
9727 
9728     // In C++11, list initializations are sequenced.
9729     SmallVector<SequenceTree::Seq, 32> Elts;
9730     SequenceTree::Seq Parent = Region;
9731     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
9732       Expr *E = ILE->getInit(I);
9733       if (!E) continue;
9734       Region = Tree.allocate(Parent);
9735       Elts.push_back(Region);
9736       Visit(E);
9737     }
9738 
9739     // Forget that the initializers are sequenced.
9740     Region = Parent;
9741     for (unsigned I = 0; I < Elts.size(); ++I)
9742       Tree.merge(Elts[I]);
9743   }
9744 };
9745 } // end anonymous namespace
9746 
9747 void Sema::CheckUnsequencedOperations(Expr *E) {
9748   SmallVector<Expr *, 8> WorkList;
9749   WorkList.push_back(E);
9750   while (!WorkList.empty()) {
9751     Expr *Item = WorkList.pop_back_val();
9752     SequenceChecker(*this, Item, WorkList);
9753   }
9754 }
9755 
9756 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
9757                               bool IsConstexpr) {
9758   CheckImplicitConversions(E, CheckLoc);
9759   if (!E->isInstantiationDependent())
9760     CheckUnsequencedOperations(E);
9761   if (!IsConstexpr && !E->isValueDependent())
9762     CheckForIntOverflow(E);
9763   DiagnoseMisalignedMembers();
9764 }
9765 
9766 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
9767                                        FieldDecl *BitField,
9768                                        Expr *Init) {
9769   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
9770 }
9771 
9772 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
9773                                          SourceLocation Loc) {
9774   if (!PType->isVariablyModifiedType())
9775     return;
9776   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
9777     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
9778     return;
9779   }
9780   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
9781     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
9782     return;
9783   }
9784   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
9785     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
9786     return;
9787   }
9788 
9789   const ArrayType *AT = S.Context.getAsArrayType(PType);
9790   if (!AT)
9791     return;
9792 
9793   if (AT->getSizeModifier() != ArrayType::Star) {
9794     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
9795     return;
9796   }
9797 
9798   S.Diag(Loc, diag::err_array_star_in_function_definition);
9799 }
9800 
9801 /// CheckParmsForFunctionDef - Check that the parameters of the given
9802 /// function are appropriate for the definition of a function. This
9803 /// takes care of any checks that cannot be performed on the
9804 /// declaration itself, e.g., that the types of each of the function
9805 /// parameters are complete.
9806 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
9807                                     bool CheckParameterNames) {
9808   bool HasInvalidParm = false;
9809   for (ParmVarDecl *Param : Parameters) {
9810     // C99 6.7.5.3p4: the parameters in a parameter type list in a
9811     // function declarator that is part of a function definition of
9812     // that function shall not have incomplete type.
9813     //
9814     // This is also C++ [dcl.fct]p6.
9815     if (!Param->isInvalidDecl() &&
9816         RequireCompleteType(Param->getLocation(), Param->getType(),
9817                             diag::err_typecheck_decl_incomplete_type)) {
9818       Param->setInvalidDecl();
9819       HasInvalidParm = true;
9820     }
9821 
9822     // C99 6.9.1p5: If the declarator includes a parameter type list, the
9823     // declaration of each parameter shall include an identifier.
9824     if (CheckParameterNames &&
9825         Param->getIdentifier() == nullptr &&
9826         !Param->isImplicit() &&
9827         !getLangOpts().CPlusPlus)
9828       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9829 
9830     // C99 6.7.5.3p12:
9831     //   If the function declarator is not part of a definition of that
9832     //   function, parameters may have incomplete type and may use the [*]
9833     //   notation in their sequences of declarator specifiers to specify
9834     //   variable length array types.
9835     QualType PType = Param->getOriginalType();
9836     // FIXME: This diagnostic should point the '[*]' if source-location
9837     // information is added for it.
9838     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
9839 
9840     // MSVC destroys objects passed by value in the callee.  Therefore a
9841     // function definition which takes such a parameter must be able to call the
9842     // object's destructor.  However, we don't perform any direct access check
9843     // on the dtor.
9844     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
9845                                        .getCXXABI()
9846                                        .areArgsDestroyedLeftToRightInCallee()) {
9847       if (!Param->isInvalidDecl()) {
9848         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
9849           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
9850           if (!ClassDecl->isInvalidDecl() &&
9851               !ClassDecl->hasIrrelevantDestructor() &&
9852               !ClassDecl->isDependentContext()) {
9853             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9854             MarkFunctionReferenced(Param->getLocation(), Destructor);
9855             DiagnoseUseOfDecl(Destructor, Param->getLocation());
9856           }
9857         }
9858       }
9859     }
9860 
9861     // Parameters with the pass_object_size attribute only need to be marked
9862     // constant at function definitions. Because we lack information about
9863     // whether we're on a declaration or definition when we're instantiating the
9864     // attribute, we need to check for constness here.
9865     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9866       if (!Param->getType().isConstQualified())
9867         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9868             << Attr->getSpelling() << 1;
9869   }
9870 
9871   return HasInvalidParm;
9872 }
9873 
9874 /// CheckCastAlign - Implements -Wcast-align, which warns when a
9875 /// pointer cast increases the alignment requirements.
9876 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9877   // This is actually a lot of work to potentially be doing on every
9878   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
9879   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
9880     return;
9881 
9882   // Ignore dependent types.
9883   if (T->isDependentType() || Op->getType()->isDependentType())
9884     return;
9885 
9886   // Require that the destination be a pointer type.
9887   const PointerType *DestPtr = T->getAs<PointerType>();
9888   if (!DestPtr) return;
9889 
9890   // If the destination has alignment 1, we're done.
9891   QualType DestPointee = DestPtr->getPointeeType();
9892   if (DestPointee->isIncompleteType()) return;
9893   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9894   if (DestAlign.isOne()) return;
9895 
9896   // Require that the source be a pointer type.
9897   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9898   if (!SrcPtr) return;
9899   QualType SrcPointee = SrcPtr->getPointeeType();
9900 
9901   // Whitelist casts from cv void*.  We already implicitly
9902   // whitelisted casts to cv void*, since they have alignment 1.
9903   // Also whitelist casts involving incomplete types, which implicitly
9904   // includes 'void'.
9905   if (SrcPointee->isIncompleteType()) return;
9906 
9907   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9908   if (SrcAlign >= DestAlign) return;
9909 
9910   Diag(TRange.getBegin(), diag::warn_cast_align)
9911     << Op->getType() << T
9912     << static_cast<unsigned>(SrcAlign.getQuantity())
9913     << static_cast<unsigned>(DestAlign.getQuantity())
9914     << TRange << Op->getSourceRange();
9915 }
9916 
9917 /// \brief Check whether this array fits the idiom of a size-one tail padded
9918 /// array member of a struct.
9919 ///
9920 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
9921 /// commonly used to emulate flexible arrays in C89 code.
9922 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
9923                                     const NamedDecl *ND) {
9924   if (Size != 1 || !ND) return false;
9925 
9926   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9927   if (!FD) return false;
9928 
9929   // Don't consider sizes resulting from macro expansions or template argument
9930   // substitution to form C89 tail-padded arrays.
9931 
9932   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
9933   while (TInfo) {
9934     TypeLoc TL = TInfo->getTypeLoc();
9935     // Look through typedefs.
9936     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9937       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
9938       TInfo = TDL->getTypeSourceInfo();
9939       continue;
9940     }
9941     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9942       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
9943       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9944         return false;
9945     }
9946     break;
9947   }
9948 
9949   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
9950   if (!RD) return false;
9951   if (RD->isUnion()) return false;
9952   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9953     if (!CRD->isStandardLayout()) return false;
9954   }
9955 
9956   // See if this is the last field decl in the record.
9957   const Decl *D = FD;
9958   while ((D = D->getNextDeclInContext()))
9959     if (isa<FieldDecl>(D))
9960       return false;
9961   return true;
9962 }
9963 
9964 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9965                             const ArraySubscriptExpr *ASE,
9966                             bool AllowOnePastEnd, bool IndexNegated) {
9967   IndexExpr = IndexExpr->IgnoreParenImpCasts();
9968   if (IndexExpr->isValueDependent())
9969     return;
9970 
9971   const Type *EffectiveType =
9972       BaseExpr->getType()->getPointeeOrArrayElementType();
9973   BaseExpr = BaseExpr->IgnoreParenCasts();
9974   const ConstantArrayType *ArrayTy =
9975     Context.getAsConstantArrayType(BaseExpr->getType());
9976   if (!ArrayTy)
9977     return;
9978 
9979   llvm::APSInt index;
9980   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
9981     return;
9982   if (IndexNegated)
9983     index = -index;
9984 
9985   const NamedDecl *ND = nullptr;
9986   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9987     ND = dyn_cast<NamedDecl>(DRE->getDecl());
9988   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9989     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9990 
9991   if (index.isUnsigned() || !index.isNegative()) {
9992     llvm::APInt size = ArrayTy->getSize();
9993     if (!size.isStrictlyPositive())
9994       return;
9995 
9996     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
9997     if (BaseType != EffectiveType) {
9998       // Make sure we're comparing apples to apples when comparing index to size
9999       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10000       uint64_t array_typesize = Context.getTypeSize(BaseType);
10001       // Handle ptrarith_typesize being zero, such as when casting to void*
10002       if (!ptrarith_typesize) ptrarith_typesize = 1;
10003       if (ptrarith_typesize != array_typesize) {
10004         // There's a cast to a different size type involved
10005         uint64_t ratio = array_typesize / ptrarith_typesize;
10006         // TODO: Be smarter about handling cases where array_typesize is not a
10007         // multiple of ptrarith_typesize
10008         if (ptrarith_typesize * ratio == array_typesize)
10009           size *= llvm::APInt(size.getBitWidth(), ratio);
10010       }
10011     }
10012 
10013     if (size.getBitWidth() > index.getBitWidth())
10014       index = index.zext(size.getBitWidth());
10015     else if (size.getBitWidth() < index.getBitWidth())
10016       size = size.zext(index.getBitWidth());
10017 
10018     // For array subscripting the index must be less than size, but for pointer
10019     // arithmetic also allow the index (offset) to be equal to size since
10020     // computing the next address after the end of the array is legal and
10021     // commonly done e.g. in C++ iterators and range-based for loops.
10022     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10023       return;
10024 
10025     // Also don't warn for arrays of size 1 which are members of some
10026     // structure. These are often used to approximate flexible arrays in C89
10027     // code.
10028     if (IsTailPaddedMemberArray(*this, size, ND))
10029       return;
10030 
10031     // Suppress the warning if the subscript expression (as identified by the
10032     // ']' location) and the index expression are both from macro expansions
10033     // within a system header.
10034     if (ASE) {
10035       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10036           ASE->getRBracketLoc());
10037       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10038         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10039             IndexExpr->getLocStart());
10040         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10041           return;
10042       }
10043     }
10044 
10045     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10046     if (ASE)
10047       DiagID = diag::warn_array_index_exceeds_bounds;
10048 
10049     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10050                         PDiag(DiagID) << index.toString(10, true)
10051                           << size.toString(10, true)
10052                           << (unsigned)size.getLimitedValue(~0U)
10053                           << IndexExpr->getSourceRange());
10054   } else {
10055     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10056     if (!ASE) {
10057       DiagID = diag::warn_ptr_arith_precedes_bounds;
10058       if (index.isNegative()) index = -index;
10059     }
10060 
10061     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10062                         PDiag(DiagID) << index.toString(10, true)
10063                           << IndexExpr->getSourceRange());
10064   }
10065 
10066   if (!ND) {
10067     // Try harder to find a NamedDecl to point at in the note.
10068     while (const ArraySubscriptExpr *ASE =
10069            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10070       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10071     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10072       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10073     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10074       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10075   }
10076 
10077   if (ND)
10078     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10079                         PDiag(diag::note_array_index_out_of_bounds)
10080                           << ND->getDeclName());
10081 }
10082 
10083 void Sema::CheckArrayAccess(const Expr *expr) {
10084   int AllowOnePastEnd = 0;
10085   while (expr) {
10086     expr = expr->IgnoreParenImpCasts();
10087     switch (expr->getStmtClass()) {
10088       case Stmt::ArraySubscriptExprClass: {
10089         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10090         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
10091                          AllowOnePastEnd > 0);
10092         return;
10093       }
10094       case Stmt::OMPArraySectionExprClass: {
10095         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
10096         if (ASE->getLowerBound())
10097           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
10098                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
10099         return;
10100       }
10101       case Stmt::UnaryOperatorClass: {
10102         // Only unwrap the * and & unary operators
10103         const UnaryOperator *UO = cast<UnaryOperator>(expr);
10104         expr = UO->getSubExpr();
10105         switch (UO->getOpcode()) {
10106           case UO_AddrOf:
10107             AllowOnePastEnd++;
10108             break;
10109           case UO_Deref:
10110             AllowOnePastEnd--;
10111             break;
10112           default:
10113             return;
10114         }
10115         break;
10116       }
10117       case Stmt::ConditionalOperatorClass: {
10118         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
10119         if (const Expr *lhs = cond->getLHS())
10120           CheckArrayAccess(lhs);
10121         if (const Expr *rhs = cond->getRHS())
10122           CheckArrayAccess(rhs);
10123         return;
10124       }
10125       default:
10126         return;
10127     }
10128   }
10129 }
10130 
10131 //===--- CHECK: Objective-C retain cycles ----------------------------------//
10132 
10133 namespace {
10134   struct RetainCycleOwner {
10135     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
10136     VarDecl *Variable;
10137     SourceRange Range;
10138     SourceLocation Loc;
10139     bool Indirect;
10140 
10141     void setLocsFrom(Expr *e) {
10142       Loc = e->getExprLoc();
10143       Range = e->getSourceRange();
10144     }
10145   };
10146 } // end anonymous namespace
10147 
10148 /// Consider whether capturing the given variable can possibly lead to
10149 /// a retain cycle.
10150 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
10151   // In ARC, it's captured strongly iff the variable has __strong
10152   // lifetime.  In MRR, it's captured strongly if the variable is
10153   // __block and has an appropriate type.
10154   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10155     return false;
10156 
10157   owner.Variable = var;
10158   if (ref)
10159     owner.setLocsFrom(ref);
10160   return true;
10161 }
10162 
10163 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
10164   while (true) {
10165     e = e->IgnoreParens();
10166     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
10167       switch (cast->getCastKind()) {
10168       case CK_BitCast:
10169       case CK_LValueBitCast:
10170       case CK_LValueToRValue:
10171       case CK_ARCReclaimReturnedObject:
10172         e = cast->getSubExpr();
10173         continue;
10174 
10175       default:
10176         return false;
10177       }
10178     }
10179 
10180     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
10181       ObjCIvarDecl *ivar = ref->getDecl();
10182       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
10183         return false;
10184 
10185       // Try to find a retain cycle in the base.
10186       if (!findRetainCycleOwner(S, ref->getBase(), owner))
10187         return false;
10188 
10189       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10190       owner.Indirect = true;
10191       return true;
10192     }
10193 
10194     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10195       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
10196       if (!var) return false;
10197       return considerVariable(var, ref, owner);
10198     }
10199 
10200     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10201       if (member->isArrow()) return false;
10202 
10203       // Don't count this as an indirect ownership.
10204       e = member->getBase();
10205       continue;
10206     }
10207 
10208     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
10209       // Only pay attention to pseudo-objects on property references.
10210       ObjCPropertyRefExpr *pre
10211         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
10212                                               ->IgnoreParens());
10213       if (!pre) return false;
10214       if (pre->isImplicitProperty()) return false;
10215       ObjCPropertyDecl *property = pre->getExplicitProperty();
10216       if (!property->isRetaining() &&
10217           !(property->getPropertyIvarDecl() &&
10218             property->getPropertyIvarDecl()->getType()
10219               .getObjCLifetime() == Qualifiers::OCL_Strong))
10220           return false;
10221 
10222       owner.Indirect = true;
10223       if (pre->isSuperReceiver()) {
10224         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
10225         if (!owner.Variable)
10226           return false;
10227         owner.Loc = pre->getLocation();
10228         owner.Range = pre->getSourceRange();
10229         return true;
10230       }
10231       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
10232                               ->getSourceExpr());
10233       continue;
10234     }
10235 
10236     // Array ivars?
10237 
10238     return false;
10239   }
10240 }
10241 
10242 namespace {
10243   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
10244     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
10245       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
10246         Context(Context), Variable(variable), Capturer(nullptr),
10247         VarWillBeReased(false) {}
10248     ASTContext &Context;
10249     VarDecl *Variable;
10250     Expr *Capturer;
10251     bool VarWillBeReased;
10252 
10253     void VisitDeclRefExpr(DeclRefExpr *ref) {
10254       if (ref->getDecl() == Variable && !Capturer)
10255         Capturer = ref;
10256     }
10257 
10258     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
10259       if (Capturer) return;
10260       Visit(ref->getBase());
10261       if (Capturer && ref->isFreeIvar())
10262         Capturer = ref;
10263     }
10264 
10265     void VisitBlockExpr(BlockExpr *block) {
10266       // Look inside nested blocks
10267       if (block->getBlockDecl()->capturesVariable(Variable))
10268         Visit(block->getBlockDecl()->getBody());
10269     }
10270 
10271     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
10272       if (Capturer) return;
10273       if (OVE->getSourceExpr())
10274         Visit(OVE->getSourceExpr());
10275     }
10276     void VisitBinaryOperator(BinaryOperator *BinOp) {
10277       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
10278         return;
10279       Expr *LHS = BinOp->getLHS();
10280       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
10281         if (DRE->getDecl() != Variable)
10282           return;
10283         if (Expr *RHS = BinOp->getRHS()) {
10284           RHS = RHS->IgnoreParenCasts();
10285           llvm::APSInt Value;
10286           VarWillBeReased =
10287             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
10288         }
10289       }
10290     }
10291   };
10292 } // end anonymous namespace
10293 
10294 /// Check whether the given argument is a block which captures a
10295 /// variable.
10296 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
10297   assert(owner.Variable && owner.Loc.isValid());
10298 
10299   e = e->IgnoreParenCasts();
10300 
10301   // Look through [^{...} copy] and Block_copy(^{...}).
10302   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
10303     Selector Cmd = ME->getSelector();
10304     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
10305       e = ME->getInstanceReceiver();
10306       if (!e)
10307         return nullptr;
10308       e = e->IgnoreParenCasts();
10309     }
10310   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
10311     if (CE->getNumArgs() == 1) {
10312       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
10313       if (Fn) {
10314         const IdentifierInfo *FnI = Fn->getIdentifier();
10315         if (FnI && FnI->isStr("_Block_copy")) {
10316           e = CE->getArg(0)->IgnoreParenCasts();
10317         }
10318       }
10319     }
10320   }
10321 
10322   BlockExpr *block = dyn_cast<BlockExpr>(e);
10323   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
10324     return nullptr;
10325 
10326   FindCaptureVisitor visitor(S.Context, owner.Variable);
10327   visitor.Visit(block->getBlockDecl()->getBody());
10328   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
10329 }
10330 
10331 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
10332                                 RetainCycleOwner &owner) {
10333   assert(capturer);
10334   assert(owner.Variable && owner.Loc.isValid());
10335 
10336   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
10337     << owner.Variable << capturer->getSourceRange();
10338   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
10339     << owner.Indirect << owner.Range;
10340 }
10341 
10342 /// Check for a keyword selector that starts with the word 'add' or
10343 /// 'set'.
10344 static bool isSetterLikeSelector(Selector sel) {
10345   if (sel.isUnarySelector()) return false;
10346 
10347   StringRef str = sel.getNameForSlot(0);
10348   while (!str.empty() && str.front() == '_') str = str.substr(1);
10349   if (str.startswith("set"))
10350     str = str.substr(3);
10351   else if (str.startswith("add")) {
10352     // Specially whitelist 'addOperationWithBlock:'.
10353     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
10354       return false;
10355     str = str.substr(3);
10356   }
10357   else
10358     return false;
10359 
10360   if (str.empty()) return true;
10361   return !isLowercase(str.front());
10362 }
10363 
10364 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
10365                                                     ObjCMessageExpr *Message) {
10366   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
10367                                                 Message->getReceiverInterface(),
10368                                                 NSAPI::ClassId_NSMutableArray);
10369   if (!IsMutableArray) {
10370     return None;
10371   }
10372 
10373   Selector Sel = Message->getSelector();
10374 
10375   Optional<NSAPI::NSArrayMethodKind> MKOpt =
10376     S.NSAPIObj->getNSArrayMethodKind(Sel);
10377   if (!MKOpt) {
10378     return None;
10379   }
10380 
10381   NSAPI::NSArrayMethodKind MK = *MKOpt;
10382 
10383   switch (MK) {
10384     case NSAPI::NSMutableArr_addObject:
10385     case NSAPI::NSMutableArr_insertObjectAtIndex:
10386     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
10387       return 0;
10388     case NSAPI::NSMutableArr_replaceObjectAtIndex:
10389       return 1;
10390 
10391     default:
10392       return None;
10393   }
10394 
10395   return None;
10396 }
10397 
10398 static
10399 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
10400                                                   ObjCMessageExpr *Message) {
10401   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
10402                                             Message->getReceiverInterface(),
10403                                             NSAPI::ClassId_NSMutableDictionary);
10404   if (!IsMutableDictionary) {
10405     return None;
10406   }
10407 
10408   Selector Sel = Message->getSelector();
10409 
10410   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
10411     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
10412   if (!MKOpt) {
10413     return None;
10414   }
10415 
10416   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
10417 
10418   switch (MK) {
10419     case NSAPI::NSMutableDict_setObjectForKey:
10420     case NSAPI::NSMutableDict_setValueForKey:
10421     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
10422       return 0;
10423 
10424     default:
10425       return None;
10426   }
10427 
10428   return None;
10429 }
10430 
10431 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
10432   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
10433                                                 Message->getReceiverInterface(),
10434                                                 NSAPI::ClassId_NSMutableSet);
10435 
10436   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
10437                                             Message->getReceiverInterface(),
10438                                             NSAPI::ClassId_NSMutableOrderedSet);
10439   if (!IsMutableSet && !IsMutableOrderedSet) {
10440     return None;
10441   }
10442 
10443   Selector Sel = Message->getSelector();
10444 
10445   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
10446   if (!MKOpt) {
10447     return None;
10448   }
10449 
10450   NSAPI::NSSetMethodKind MK = *MKOpt;
10451 
10452   switch (MK) {
10453     case NSAPI::NSMutableSet_addObject:
10454     case NSAPI::NSOrderedSet_setObjectAtIndex:
10455     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
10456     case NSAPI::NSOrderedSet_insertObjectAtIndex:
10457       return 0;
10458     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
10459       return 1;
10460   }
10461 
10462   return None;
10463 }
10464 
10465 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
10466   if (!Message->isInstanceMessage()) {
10467     return;
10468   }
10469 
10470   Optional<int> ArgOpt;
10471 
10472   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
10473       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
10474       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
10475     return;
10476   }
10477 
10478   int ArgIndex = *ArgOpt;
10479 
10480   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
10481   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
10482     Arg = OE->getSourceExpr()->IgnoreImpCasts();
10483   }
10484 
10485   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
10486     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10487       if (ArgRE->isObjCSelfExpr()) {
10488         Diag(Message->getSourceRange().getBegin(),
10489              diag::warn_objc_circular_container)
10490           << ArgRE->getDecl()->getName() << StringRef("super");
10491       }
10492     }
10493   } else {
10494     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
10495 
10496     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
10497       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
10498     }
10499 
10500     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
10501       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
10502         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
10503           ValueDecl *Decl = ReceiverRE->getDecl();
10504           Diag(Message->getSourceRange().getBegin(),
10505                diag::warn_objc_circular_container)
10506             << Decl->getName() << Decl->getName();
10507           if (!ArgRE->isObjCSelfExpr()) {
10508             Diag(Decl->getLocation(),
10509                  diag::note_objc_circular_container_declared_here)
10510               << Decl->getName();
10511           }
10512         }
10513       }
10514     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
10515       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
10516         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
10517           ObjCIvarDecl *Decl = IvarRE->getDecl();
10518           Diag(Message->getSourceRange().getBegin(),
10519                diag::warn_objc_circular_container)
10520             << Decl->getName() << Decl->getName();
10521           Diag(Decl->getLocation(),
10522                diag::note_objc_circular_container_declared_here)
10523             << Decl->getName();
10524         }
10525       }
10526     }
10527   }
10528 }
10529 
10530 /// Check a message send to see if it's likely to cause a retain cycle.
10531 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
10532   // Only check instance methods whose selector looks like a setter.
10533   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
10534     return;
10535 
10536   // Try to find a variable that the receiver is strongly owned by.
10537   RetainCycleOwner owner;
10538   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
10539     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
10540       return;
10541   } else {
10542     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
10543     owner.Variable = getCurMethodDecl()->getSelfDecl();
10544     owner.Loc = msg->getSuperLoc();
10545     owner.Range = msg->getSuperLoc();
10546   }
10547 
10548   // Check whether the receiver is captured by any of the arguments.
10549   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
10550     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
10551       return diagnoseRetainCycle(*this, capturer, owner);
10552 }
10553 
10554 /// Check a property assign to see if it's likely to cause a retain cycle.
10555 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
10556   RetainCycleOwner owner;
10557   if (!findRetainCycleOwner(*this, receiver, owner))
10558     return;
10559 
10560   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
10561     diagnoseRetainCycle(*this, capturer, owner);
10562 }
10563 
10564 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
10565   RetainCycleOwner Owner;
10566   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
10567     return;
10568 
10569   // Because we don't have an expression for the variable, we have to set the
10570   // location explicitly here.
10571   Owner.Loc = Var->getLocation();
10572   Owner.Range = Var->getSourceRange();
10573 
10574   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
10575     diagnoseRetainCycle(*this, Capturer, Owner);
10576 }
10577 
10578 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
10579                                      Expr *RHS, bool isProperty) {
10580   // Check if RHS is an Objective-C object literal, which also can get
10581   // immediately zapped in a weak reference.  Note that we explicitly
10582   // allow ObjCStringLiterals, since those are designed to never really die.
10583   RHS = RHS->IgnoreParenImpCasts();
10584 
10585   // This enum needs to match with the 'select' in
10586   // warn_objc_arc_literal_assign (off-by-1).
10587   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
10588   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
10589     return false;
10590 
10591   S.Diag(Loc, diag::warn_arc_literal_assign)
10592     << (unsigned) Kind
10593     << (isProperty ? 0 : 1)
10594     << RHS->getSourceRange();
10595 
10596   return true;
10597 }
10598 
10599 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
10600                                     Qualifiers::ObjCLifetime LT,
10601                                     Expr *RHS, bool isProperty) {
10602   // Strip off any implicit cast added to get to the one ARC-specific.
10603   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10604     if (cast->getCastKind() == CK_ARCConsumeObject) {
10605       S.Diag(Loc, diag::warn_arc_retained_assign)
10606         << (LT == Qualifiers::OCL_ExplicitNone)
10607         << (isProperty ? 0 : 1)
10608         << RHS->getSourceRange();
10609       return true;
10610     }
10611     RHS = cast->getSubExpr();
10612   }
10613 
10614   if (LT == Qualifiers::OCL_Weak &&
10615       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
10616     return true;
10617 
10618   return false;
10619 }
10620 
10621 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
10622                               QualType LHS, Expr *RHS) {
10623   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
10624 
10625   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
10626     return false;
10627 
10628   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
10629     return true;
10630 
10631   return false;
10632 }
10633 
10634 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
10635                               Expr *LHS, Expr *RHS) {
10636   QualType LHSType;
10637   // PropertyRef on LHS type need be directly obtained from
10638   // its declaration as it has a PseudoType.
10639   ObjCPropertyRefExpr *PRE
10640     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
10641   if (PRE && !PRE->isImplicitProperty()) {
10642     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10643     if (PD)
10644       LHSType = PD->getType();
10645   }
10646 
10647   if (LHSType.isNull())
10648     LHSType = LHS->getType();
10649 
10650   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
10651 
10652   if (LT == Qualifiers::OCL_Weak) {
10653     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
10654       getCurFunction()->markSafeWeakUse(LHS);
10655   }
10656 
10657   if (checkUnsafeAssigns(Loc, LHSType, RHS))
10658     return;
10659 
10660   // FIXME. Check for other life times.
10661   if (LT != Qualifiers::OCL_None)
10662     return;
10663 
10664   if (PRE) {
10665     if (PRE->isImplicitProperty())
10666       return;
10667     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
10668     if (!PD)
10669       return;
10670 
10671     unsigned Attributes = PD->getPropertyAttributes();
10672     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
10673       // when 'assign' attribute was not explicitly specified
10674       // by user, ignore it and rely on property type itself
10675       // for lifetime info.
10676       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
10677       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
10678           LHSType->isObjCRetainableType())
10679         return;
10680 
10681       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
10682         if (cast->getCastKind() == CK_ARCConsumeObject) {
10683           Diag(Loc, diag::warn_arc_retained_property_assign)
10684           << RHS->getSourceRange();
10685           return;
10686         }
10687         RHS = cast->getSubExpr();
10688       }
10689     }
10690     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
10691       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
10692         return;
10693     }
10694   }
10695 }
10696 
10697 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
10698 
10699 namespace {
10700 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
10701                                  SourceLocation StmtLoc,
10702                                  const NullStmt *Body) {
10703   // Do not warn if the body is a macro that expands to nothing, e.g:
10704   //
10705   // #define CALL(x)
10706   // if (condition)
10707   //   CALL(0);
10708   //
10709   if (Body->hasLeadingEmptyMacro())
10710     return false;
10711 
10712   // Get line numbers of statement and body.
10713   bool StmtLineInvalid;
10714   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
10715                                                       &StmtLineInvalid);
10716   if (StmtLineInvalid)
10717     return false;
10718 
10719   bool BodyLineInvalid;
10720   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
10721                                                       &BodyLineInvalid);
10722   if (BodyLineInvalid)
10723     return false;
10724 
10725   // Warn if null statement and body are on the same line.
10726   if (StmtLine != BodyLine)
10727     return false;
10728 
10729   return true;
10730 }
10731 } // end anonymous namespace
10732 
10733 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
10734                                  const Stmt *Body,
10735                                  unsigned DiagID) {
10736   // Since this is a syntactic check, don't emit diagnostic for template
10737   // instantiations, this just adds noise.
10738   if (CurrentInstantiationScope)
10739     return;
10740 
10741   // The body should be a null statement.
10742   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10743   if (!NBody)
10744     return;
10745 
10746   // Do the usual checks.
10747   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10748     return;
10749 
10750   Diag(NBody->getSemiLoc(), DiagID);
10751   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10752 }
10753 
10754 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
10755                                  const Stmt *PossibleBody) {
10756   assert(!CurrentInstantiationScope); // Ensured by caller
10757 
10758   SourceLocation StmtLoc;
10759   const Stmt *Body;
10760   unsigned DiagID;
10761   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
10762     StmtLoc = FS->getRParenLoc();
10763     Body = FS->getBody();
10764     DiagID = diag::warn_empty_for_body;
10765   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
10766     StmtLoc = WS->getCond()->getSourceRange().getEnd();
10767     Body = WS->getBody();
10768     DiagID = diag::warn_empty_while_body;
10769   } else
10770     return; // Neither `for' nor `while'.
10771 
10772   // The body should be a null statement.
10773   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
10774   if (!NBody)
10775     return;
10776 
10777   // Skip expensive checks if diagnostic is disabled.
10778   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
10779     return;
10780 
10781   // Do the usual checks.
10782   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
10783     return;
10784 
10785   // `for(...);' and `while(...);' are popular idioms, so in order to keep
10786   // noise level low, emit diagnostics only if for/while is followed by a
10787   // CompoundStmt, e.g.:
10788   //    for (int i = 0; i < n; i++);
10789   //    {
10790   //      a(i);
10791   //    }
10792   // or if for/while is followed by a statement with more indentation
10793   // than for/while itself:
10794   //    for (int i = 0; i < n; i++);
10795   //      a(i);
10796   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
10797   if (!ProbableTypo) {
10798     bool BodyColInvalid;
10799     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
10800                              PossibleBody->getLocStart(),
10801                              &BodyColInvalid);
10802     if (BodyColInvalid)
10803       return;
10804 
10805     bool StmtColInvalid;
10806     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
10807                              S->getLocStart(),
10808                              &StmtColInvalid);
10809     if (StmtColInvalid)
10810       return;
10811 
10812     if (BodyCol > StmtCol)
10813       ProbableTypo = true;
10814   }
10815 
10816   if (ProbableTypo) {
10817     Diag(NBody->getSemiLoc(), DiagID);
10818     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
10819   }
10820 }
10821 
10822 //===--- CHECK: Warn on self move with std::move. -------------------------===//
10823 
10824 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
10825 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
10826                              SourceLocation OpLoc) {
10827   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
10828     return;
10829 
10830   if (!ActiveTemplateInstantiations.empty())
10831     return;
10832 
10833   // Strip parens and casts away.
10834   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10835   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10836 
10837   // Check for a call expression
10838   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
10839   if (!CE || CE->getNumArgs() != 1)
10840     return;
10841 
10842   // Check for a call to std::move
10843   const FunctionDecl *FD = CE->getDirectCallee();
10844   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
10845       !FD->getIdentifier()->isStr("move"))
10846     return;
10847 
10848   // Get argument from std::move
10849   RHSExpr = CE->getArg(0);
10850 
10851   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10852   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10853 
10854   // Two DeclRefExpr's, check that the decls are the same.
10855   if (LHSDeclRef && RHSDeclRef) {
10856     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10857       return;
10858     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10859         RHSDeclRef->getDecl()->getCanonicalDecl())
10860       return;
10861 
10862     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10863                                         << LHSExpr->getSourceRange()
10864                                         << RHSExpr->getSourceRange();
10865     return;
10866   }
10867 
10868   // Member variables require a different approach to check for self moves.
10869   // MemberExpr's are the same if every nested MemberExpr refers to the same
10870   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10871   // the base Expr's are CXXThisExpr's.
10872   const Expr *LHSBase = LHSExpr;
10873   const Expr *RHSBase = RHSExpr;
10874   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10875   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10876   if (!LHSME || !RHSME)
10877     return;
10878 
10879   while (LHSME && RHSME) {
10880     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10881         RHSME->getMemberDecl()->getCanonicalDecl())
10882       return;
10883 
10884     LHSBase = LHSME->getBase();
10885     RHSBase = RHSME->getBase();
10886     LHSME = dyn_cast<MemberExpr>(LHSBase);
10887     RHSME = dyn_cast<MemberExpr>(RHSBase);
10888   }
10889 
10890   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10891   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10892   if (LHSDeclRef && RHSDeclRef) {
10893     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10894       return;
10895     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10896         RHSDeclRef->getDecl()->getCanonicalDecl())
10897       return;
10898 
10899     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10900                                         << LHSExpr->getSourceRange()
10901                                         << RHSExpr->getSourceRange();
10902     return;
10903   }
10904 
10905   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10906     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10907                                         << LHSExpr->getSourceRange()
10908                                         << RHSExpr->getSourceRange();
10909 }
10910 
10911 //===--- Layout compatibility ----------------------------------------------//
10912 
10913 namespace {
10914 
10915 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10916 
10917 /// \brief Check if two enumeration types are layout-compatible.
10918 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10919   // C++11 [dcl.enum] p8:
10920   // Two enumeration types are layout-compatible if they have the same
10921   // underlying type.
10922   return ED1->isComplete() && ED2->isComplete() &&
10923          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10924 }
10925 
10926 /// \brief Check if two fields are layout-compatible.
10927 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10928   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10929     return false;
10930 
10931   if (Field1->isBitField() != Field2->isBitField())
10932     return false;
10933 
10934   if (Field1->isBitField()) {
10935     // Make sure that the bit-fields are the same length.
10936     unsigned Bits1 = Field1->getBitWidthValue(C);
10937     unsigned Bits2 = Field2->getBitWidthValue(C);
10938 
10939     if (Bits1 != Bits2)
10940       return false;
10941   }
10942 
10943   return true;
10944 }
10945 
10946 /// \brief Check if two standard-layout structs are layout-compatible.
10947 /// (C++11 [class.mem] p17)
10948 bool isLayoutCompatibleStruct(ASTContext &C,
10949                               RecordDecl *RD1,
10950                               RecordDecl *RD2) {
10951   // If both records are C++ classes, check that base classes match.
10952   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10953     // If one of records is a CXXRecordDecl we are in C++ mode,
10954     // thus the other one is a CXXRecordDecl, too.
10955     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10956     // Check number of base classes.
10957     if (D1CXX->getNumBases() != D2CXX->getNumBases())
10958       return false;
10959 
10960     // Check the base classes.
10961     for (CXXRecordDecl::base_class_const_iterator
10962                Base1 = D1CXX->bases_begin(),
10963            BaseEnd1 = D1CXX->bases_end(),
10964               Base2 = D2CXX->bases_begin();
10965          Base1 != BaseEnd1;
10966          ++Base1, ++Base2) {
10967       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10968         return false;
10969     }
10970   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10971     // If only RD2 is a C++ class, it should have zero base classes.
10972     if (D2CXX->getNumBases() > 0)
10973       return false;
10974   }
10975 
10976   // Check the fields.
10977   RecordDecl::field_iterator Field2 = RD2->field_begin(),
10978                              Field2End = RD2->field_end(),
10979                              Field1 = RD1->field_begin(),
10980                              Field1End = RD1->field_end();
10981   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10982     if (!isLayoutCompatible(C, *Field1, *Field2))
10983       return false;
10984   }
10985   if (Field1 != Field1End || Field2 != Field2End)
10986     return false;
10987 
10988   return true;
10989 }
10990 
10991 /// \brief Check if two standard-layout unions are layout-compatible.
10992 /// (C++11 [class.mem] p18)
10993 bool isLayoutCompatibleUnion(ASTContext &C,
10994                              RecordDecl *RD1,
10995                              RecordDecl *RD2) {
10996   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10997   for (auto *Field2 : RD2->fields())
10998     UnmatchedFields.insert(Field2);
10999 
11000   for (auto *Field1 : RD1->fields()) {
11001     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11002         I = UnmatchedFields.begin(),
11003         E = UnmatchedFields.end();
11004 
11005     for ( ; I != E; ++I) {
11006       if (isLayoutCompatible(C, Field1, *I)) {
11007         bool Result = UnmatchedFields.erase(*I);
11008         (void) Result;
11009         assert(Result);
11010         break;
11011       }
11012     }
11013     if (I == E)
11014       return false;
11015   }
11016 
11017   return UnmatchedFields.empty();
11018 }
11019 
11020 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11021   if (RD1->isUnion() != RD2->isUnion())
11022     return false;
11023 
11024   if (RD1->isUnion())
11025     return isLayoutCompatibleUnion(C, RD1, RD2);
11026   else
11027     return isLayoutCompatibleStruct(C, RD1, RD2);
11028 }
11029 
11030 /// \brief Check if two types are layout-compatible in C++11 sense.
11031 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11032   if (T1.isNull() || T2.isNull())
11033     return false;
11034 
11035   // C++11 [basic.types] p11:
11036   // If two types T1 and T2 are the same type, then T1 and T2 are
11037   // layout-compatible types.
11038   if (C.hasSameType(T1, T2))
11039     return true;
11040 
11041   T1 = T1.getCanonicalType().getUnqualifiedType();
11042   T2 = T2.getCanonicalType().getUnqualifiedType();
11043 
11044   const Type::TypeClass TC1 = T1->getTypeClass();
11045   const Type::TypeClass TC2 = T2->getTypeClass();
11046 
11047   if (TC1 != TC2)
11048     return false;
11049 
11050   if (TC1 == Type::Enum) {
11051     return isLayoutCompatible(C,
11052                               cast<EnumType>(T1)->getDecl(),
11053                               cast<EnumType>(T2)->getDecl());
11054   } else if (TC1 == Type::Record) {
11055     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11056       return false;
11057 
11058     return isLayoutCompatible(C,
11059                               cast<RecordType>(T1)->getDecl(),
11060                               cast<RecordType>(T2)->getDecl());
11061   }
11062 
11063   return false;
11064 }
11065 } // end anonymous namespace
11066 
11067 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11068 
11069 namespace {
11070 /// \brief Given a type tag expression find the type tag itself.
11071 ///
11072 /// \param TypeExpr Type tag expression, as it appears in user's code.
11073 ///
11074 /// \param VD Declaration of an identifier that appears in a type tag.
11075 ///
11076 /// \param MagicValue Type tag magic value.
11077 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11078                      const ValueDecl **VD, uint64_t *MagicValue) {
11079   while(true) {
11080     if (!TypeExpr)
11081       return false;
11082 
11083     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11084 
11085     switch (TypeExpr->getStmtClass()) {
11086     case Stmt::UnaryOperatorClass: {
11087       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
11088       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
11089         TypeExpr = UO->getSubExpr();
11090         continue;
11091       }
11092       return false;
11093     }
11094 
11095     case Stmt::DeclRefExprClass: {
11096       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11097       *VD = DRE->getDecl();
11098       return true;
11099     }
11100 
11101     case Stmt::IntegerLiteralClass: {
11102       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
11103       llvm::APInt MagicValueAPInt = IL->getValue();
11104       if (MagicValueAPInt.getActiveBits() <= 64) {
11105         *MagicValue = MagicValueAPInt.getZExtValue();
11106         return true;
11107       } else
11108         return false;
11109     }
11110 
11111     case Stmt::BinaryConditionalOperatorClass:
11112     case Stmt::ConditionalOperatorClass: {
11113       const AbstractConditionalOperator *ACO =
11114           cast<AbstractConditionalOperator>(TypeExpr);
11115       bool Result;
11116       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
11117         if (Result)
11118           TypeExpr = ACO->getTrueExpr();
11119         else
11120           TypeExpr = ACO->getFalseExpr();
11121         continue;
11122       }
11123       return false;
11124     }
11125 
11126     case Stmt::BinaryOperatorClass: {
11127       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
11128       if (BO->getOpcode() == BO_Comma) {
11129         TypeExpr = BO->getRHS();
11130         continue;
11131       }
11132       return false;
11133     }
11134 
11135     default:
11136       return false;
11137     }
11138   }
11139 }
11140 
11141 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
11142 ///
11143 /// \param TypeExpr Expression that specifies a type tag.
11144 ///
11145 /// \param MagicValues Registered magic values.
11146 ///
11147 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
11148 ///        kind.
11149 ///
11150 /// \param TypeInfo Information about the corresponding C type.
11151 ///
11152 /// \returns true if the corresponding C type was found.
11153 bool GetMatchingCType(
11154         const IdentifierInfo *ArgumentKind,
11155         const Expr *TypeExpr, const ASTContext &Ctx,
11156         const llvm::DenseMap<Sema::TypeTagMagicValue,
11157                              Sema::TypeTagData> *MagicValues,
11158         bool &FoundWrongKind,
11159         Sema::TypeTagData &TypeInfo) {
11160   FoundWrongKind = false;
11161 
11162   // Variable declaration that has type_tag_for_datatype attribute.
11163   const ValueDecl *VD = nullptr;
11164 
11165   uint64_t MagicValue;
11166 
11167   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11168     return false;
11169 
11170   if (VD) {
11171     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
11172       if (I->getArgumentKind() != ArgumentKind) {
11173         FoundWrongKind = true;
11174         return false;
11175       }
11176       TypeInfo.Type = I->getMatchingCType();
11177       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
11178       TypeInfo.MustBeNull = I->getMustBeNull();
11179       return true;
11180     }
11181     return false;
11182   }
11183 
11184   if (!MagicValues)
11185     return false;
11186 
11187   llvm::DenseMap<Sema::TypeTagMagicValue,
11188                  Sema::TypeTagData>::const_iterator I =
11189       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11190   if (I == MagicValues->end())
11191     return false;
11192 
11193   TypeInfo = I->second;
11194   return true;
11195 }
11196 } // end anonymous namespace
11197 
11198 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
11199                                       uint64_t MagicValue, QualType Type,
11200                                       bool LayoutCompatible,
11201                                       bool MustBeNull) {
11202   if (!TypeTagForDatatypeMagicValues)
11203     TypeTagForDatatypeMagicValues.reset(
11204         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11205 
11206   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
11207   (*TypeTagForDatatypeMagicValues)[Magic] =
11208       TypeTagData(Type, LayoutCompatible, MustBeNull);
11209 }
11210 
11211 namespace {
11212 bool IsSameCharType(QualType T1, QualType T2) {
11213   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
11214   if (!BT1)
11215     return false;
11216 
11217   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
11218   if (!BT2)
11219     return false;
11220 
11221   BuiltinType::Kind T1Kind = BT1->getKind();
11222   BuiltinType::Kind T2Kind = BT2->getKind();
11223 
11224   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
11225          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
11226          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11227          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11228 }
11229 } // end anonymous namespace
11230 
11231 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
11232                                     const Expr * const *ExprArgs) {
11233   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
11234   bool IsPointerAttr = Attr->getIsPointer();
11235 
11236   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11237   bool FoundWrongKind;
11238   TypeTagData TypeInfo;
11239   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11240                         TypeTagForDatatypeMagicValues.get(),
11241                         FoundWrongKind, TypeInfo)) {
11242     if (FoundWrongKind)
11243       Diag(TypeTagExpr->getExprLoc(),
11244            diag::warn_type_tag_for_datatype_wrong_kind)
11245         << TypeTagExpr->getSourceRange();
11246     return;
11247   }
11248 
11249   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11250   if (IsPointerAttr) {
11251     // Skip implicit cast of pointer to `void *' (as a function argument).
11252     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11253       if (ICE->getType()->isVoidPointerType() &&
11254           ICE->getCastKind() == CK_BitCast)
11255         ArgumentExpr = ICE->getSubExpr();
11256   }
11257   QualType ArgumentType = ArgumentExpr->getType();
11258 
11259   // Passing a `void*' pointer shouldn't trigger a warning.
11260   if (IsPointerAttr && ArgumentType->isVoidPointerType())
11261     return;
11262 
11263   if (TypeInfo.MustBeNull) {
11264     // Type tag with matching void type requires a null pointer.
11265     if (!ArgumentExpr->isNullPointerConstant(Context,
11266                                              Expr::NPC_ValueDependentIsNotNull)) {
11267       Diag(ArgumentExpr->getExprLoc(),
11268            diag::warn_type_safety_null_pointer_required)
11269           << ArgumentKind->getName()
11270           << ArgumentExpr->getSourceRange()
11271           << TypeTagExpr->getSourceRange();
11272     }
11273     return;
11274   }
11275 
11276   QualType RequiredType = TypeInfo.Type;
11277   if (IsPointerAttr)
11278     RequiredType = Context.getPointerType(RequiredType);
11279 
11280   bool mismatch = false;
11281   if (!TypeInfo.LayoutCompatible) {
11282     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
11283 
11284     // C++11 [basic.fundamental] p1:
11285     // Plain char, signed char, and unsigned char are three distinct types.
11286     //
11287     // But we treat plain `char' as equivalent to `signed char' or `unsigned
11288     // char' depending on the current char signedness mode.
11289     if (mismatch)
11290       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
11291                                            RequiredType->getPointeeType())) ||
11292           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
11293         mismatch = false;
11294   } else
11295     if (IsPointerAttr)
11296       mismatch = !isLayoutCompatible(Context,
11297                                      ArgumentType->getPointeeType(),
11298                                      RequiredType->getPointeeType());
11299     else
11300       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
11301 
11302   if (mismatch)
11303     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
11304         << ArgumentType << ArgumentKind
11305         << TypeInfo.LayoutCompatible << RequiredType
11306         << ArgumentExpr->getSourceRange()
11307         << TypeTagExpr->getSourceRange();
11308 }
11309 
11310 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
11311                                          CharUnits Alignment) {
11312   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
11313 }
11314 
11315 void Sema::DiagnoseMisalignedMembers() {
11316   for (MisalignedMember &m : MisalignedMembers) {
11317     const NamedDecl *ND = m.RD;
11318     if (ND->getName().empty()) {
11319       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
11320         ND = TD;
11321     }
11322     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
11323         << m.MD << ND << m.E->getSourceRange();
11324   }
11325   MisalignedMembers.clear();
11326 }
11327 
11328 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
11329   if (!T->isPointerType())
11330     return;
11331   if (isa<UnaryOperator>(E) &&
11332       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
11333     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11334     if (isa<MemberExpr>(Op)) {
11335       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
11336                           MisalignedMember(Op));
11337       if (MA != MisalignedMembers.end() &&
11338           Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)
11339         MisalignedMembers.erase(MA);
11340     }
11341   }
11342 }
11343 
11344 void Sema::RefersToMemberWithReducedAlignment(
11345     Expr *E,
11346     std::function<void(Expr *, RecordDecl *, ValueDecl *, CharUnits)> Action) {
11347   const auto *ME = dyn_cast<MemberExpr>(E);
11348   while (ME && isa<FieldDecl>(ME->getMemberDecl())) {
11349     QualType BaseType = ME->getBase()->getType();
11350     if (ME->isArrow())
11351       BaseType = BaseType->getPointeeType();
11352     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
11353 
11354     ValueDecl *MD = ME->getMemberDecl();
11355     bool ByteAligned = Context.getTypeAlignInChars(MD->getType()).isOne();
11356     if (ByteAligned) // Attribute packed does not have any effect.
11357       break;
11358 
11359     if (!ByteAligned &&
11360         (RD->hasAttr<PackedAttr>() || (MD->hasAttr<PackedAttr>()))) {
11361       CharUnits Alignment = std::min(Context.getTypeAlignInChars(MD->getType()),
11362                                      Context.getTypeAlignInChars(BaseType));
11363       // Notify that this expression designates a member with reduced alignment
11364       Action(E, RD, MD, Alignment);
11365       break;
11366     }
11367     ME = dyn_cast<MemberExpr>(ME->getBase());
11368   }
11369 }
11370 
11371 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
11372   using namespace std::placeholders;
11373   RefersToMemberWithReducedAlignment(
11374       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
11375                      _2, _3, _4));
11376 }
11377 
11378