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