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/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.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/Preprocessor.h"
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 "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <limits>
41 using namespace clang;
42 using namespace sema;
43 
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                     unsigned ByteNo) const {
46   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47                                PP.getLangOpts(), PP.getTargetInfo());
48 }
49 
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking.  Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53   unsigned argCount = call->getNumArgs();
54   if (argCount == desiredArgCount) return false;
55 
56   if (argCount < desiredArgCount)
57     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58         << 0 /*function call*/ << desiredArgCount << argCount
59         << call->getSourceRange();
60 
61   // Highlight all the excess arguments.
62   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                     call->getArg(argCount - 1)->getLocEnd());
64 
65   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66     << 0 /*function call*/ << desiredArgCount << argCount
67     << call->getArg(1)->getSourceRange();
68 }
69 
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73   if (checkArgCount(S, TheCall, 2))
74     return true;
75 
76   // First argument should be an integer.
77   Expr *ValArg = TheCall->getArg(0);
78   QualType Ty = ValArg->getType();
79   if (!Ty->isIntegerType()) {
80     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81       << ValArg->getSourceRange();
82     return true;
83   }
84 
85   // Second argument should be a constant string.
86   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88   if (!Literal || !Literal->isAscii()) {
89     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90       << StrArg->getSourceRange();
91     return true;
92   }
93 
94   TheCall->setType(Ty);
95   return false;
96 }
97 
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101   if (checkArgCount(S, TheCall, 1))
102     return true;
103 
104   ExprResult Arg(S.Owned(TheCall->getArg(0)));
105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106   if (ResultType.isNull())
107     return true;
108 
109   TheCall->setArg(0, Arg.take());
110   TheCall->setType(ResultType);
111   return false;
112 }
113 
114 ExprResult
115 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116   ExprResult TheCallResult(Owned(TheCall));
117 
118   // Find out if any arguments are required to be integer constant expressions.
119   unsigned ICEArguments = 0;
120   ASTContext::GetBuiltinTypeError Error;
121   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122   if (Error != ASTContext::GE_None)
123     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
124 
125   // If any arguments are required to be ICE's, check and diagnose.
126   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127     // Skip arguments not required to be ICE's.
128     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129 
130     llvm::APSInt Result;
131     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132       return true;
133     ICEArguments &= ~(1 << ArgNo);
134   }
135 
136   switch (BuiltinID) {
137   case Builtin::BI__builtin___CFStringMakeConstantString:
138     assert(TheCall->getNumArgs() == 1 &&
139            "Wrong # arguments to builtin CFStringMakeConstantString");
140     if (CheckObjCString(TheCall->getArg(0)))
141       return ExprError();
142     break;
143   case Builtin::BI__builtin_stdarg_start:
144   case Builtin::BI__builtin_va_start:
145     if (SemaBuiltinVAStart(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_isgreater:
149   case Builtin::BI__builtin_isgreaterequal:
150   case Builtin::BI__builtin_isless:
151   case Builtin::BI__builtin_islessequal:
152   case Builtin::BI__builtin_islessgreater:
153   case Builtin::BI__builtin_isunordered:
154     if (SemaBuiltinUnorderedCompare(TheCall))
155       return ExprError();
156     break;
157   case Builtin::BI__builtin_fpclassify:
158     if (SemaBuiltinFPClassification(TheCall, 6))
159       return ExprError();
160     break;
161   case Builtin::BI__builtin_isfinite:
162   case Builtin::BI__builtin_isinf:
163   case Builtin::BI__builtin_isinf_sign:
164   case Builtin::BI__builtin_isnan:
165   case Builtin::BI__builtin_isnormal:
166     if (SemaBuiltinFPClassification(TheCall, 1))
167       return ExprError();
168     break;
169   case Builtin::BI__builtin_shufflevector:
170     return SemaBuiltinShuffleVector(TheCall);
171     // TheCall will be freed by the smart pointer here, but that's fine, since
172     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173   case Builtin::BI__builtin_prefetch:
174     if (SemaBuiltinPrefetch(TheCall))
175       return ExprError();
176     break;
177   case Builtin::BI__builtin_object_size:
178     if (SemaBuiltinObjectSize(TheCall))
179       return ExprError();
180     break;
181   case Builtin::BI__builtin_longjmp:
182     if (SemaBuiltinLongjmp(TheCall))
183       return ExprError();
184     break;
185 
186   case Builtin::BI__builtin_classify_type:
187     if (checkArgCount(*this, TheCall, 1)) return true;
188     TheCall->setType(Context.IntTy);
189     break;
190   case Builtin::BI__builtin_constant_p:
191     if (checkArgCount(*this, TheCall, 1)) return true;
192     TheCall->setType(Context.IntTy);
193     break;
194   case Builtin::BI__sync_fetch_and_add:
195   case Builtin::BI__sync_fetch_and_add_1:
196   case Builtin::BI__sync_fetch_and_add_2:
197   case Builtin::BI__sync_fetch_and_add_4:
198   case Builtin::BI__sync_fetch_and_add_8:
199   case Builtin::BI__sync_fetch_and_add_16:
200   case Builtin::BI__sync_fetch_and_sub:
201   case Builtin::BI__sync_fetch_and_sub_1:
202   case Builtin::BI__sync_fetch_and_sub_2:
203   case Builtin::BI__sync_fetch_and_sub_4:
204   case Builtin::BI__sync_fetch_and_sub_8:
205   case Builtin::BI__sync_fetch_and_sub_16:
206   case Builtin::BI__sync_fetch_and_or:
207   case Builtin::BI__sync_fetch_and_or_1:
208   case Builtin::BI__sync_fetch_and_or_2:
209   case Builtin::BI__sync_fetch_and_or_4:
210   case Builtin::BI__sync_fetch_and_or_8:
211   case Builtin::BI__sync_fetch_and_or_16:
212   case Builtin::BI__sync_fetch_and_and:
213   case Builtin::BI__sync_fetch_and_and_1:
214   case Builtin::BI__sync_fetch_and_and_2:
215   case Builtin::BI__sync_fetch_and_and_4:
216   case Builtin::BI__sync_fetch_and_and_8:
217   case Builtin::BI__sync_fetch_and_and_16:
218   case Builtin::BI__sync_fetch_and_xor:
219   case Builtin::BI__sync_fetch_and_xor_1:
220   case Builtin::BI__sync_fetch_and_xor_2:
221   case Builtin::BI__sync_fetch_and_xor_4:
222   case Builtin::BI__sync_fetch_and_xor_8:
223   case Builtin::BI__sync_fetch_and_xor_16:
224   case Builtin::BI__sync_add_and_fetch:
225   case Builtin::BI__sync_add_and_fetch_1:
226   case Builtin::BI__sync_add_and_fetch_2:
227   case Builtin::BI__sync_add_and_fetch_4:
228   case Builtin::BI__sync_add_and_fetch_8:
229   case Builtin::BI__sync_add_and_fetch_16:
230   case Builtin::BI__sync_sub_and_fetch:
231   case Builtin::BI__sync_sub_and_fetch_1:
232   case Builtin::BI__sync_sub_and_fetch_2:
233   case Builtin::BI__sync_sub_and_fetch_4:
234   case Builtin::BI__sync_sub_and_fetch_8:
235   case Builtin::BI__sync_sub_and_fetch_16:
236   case Builtin::BI__sync_and_and_fetch:
237   case Builtin::BI__sync_and_and_fetch_1:
238   case Builtin::BI__sync_and_and_fetch_2:
239   case Builtin::BI__sync_and_and_fetch_4:
240   case Builtin::BI__sync_and_and_fetch_8:
241   case Builtin::BI__sync_and_and_fetch_16:
242   case Builtin::BI__sync_or_and_fetch:
243   case Builtin::BI__sync_or_and_fetch_1:
244   case Builtin::BI__sync_or_and_fetch_2:
245   case Builtin::BI__sync_or_and_fetch_4:
246   case Builtin::BI__sync_or_and_fetch_8:
247   case Builtin::BI__sync_or_and_fetch_16:
248   case Builtin::BI__sync_xor_and_fetch:
249   case Builtin::BI__sync_xor_and_fetch_1:
250   case Builtin::BI__sync_xor_and_fetch_2:
251   case Builtin::BI__sync_xor_and_fetch_4:
252   case Builtin::BI__sync_xor_and_fetch_8:
253   case Builtin::BI__sync_xor_and_fetch_16:
254   case Builtin::BI__sync_val_compare_and_swap:
255   case Builtin::BI__sync_val_compare_and_swap_1:
256   case Builtin::BI__sync_val_compare_and_swap_2:
257   case Builtin::BI__sync_val_compare_and_swap_4:
258   case Builtin::BI__sync_val_compare_and_swap_8:
259   case Builtin::BI__sync_val_compare_and_swap_16:
260   case Builtin::BI__sync_bool_compare_and_swap:
261   case Builtin::BI__sync_bool_compare_and_swap_1:
262   case Builtin::BI__sync_bool_compare_and_swap_2:
263   case Builtin::BI__sync_bool_compare_and_swap_4:
264   case Builtin::BI__sync_bool_compare_and_swap_8:
265   case Builtin::BI__sync_bool_compare_and_swap_16:
266   case Builtin::BI__sync_lock_test_and_set:
267   case Builtin::BI__sync_lock_test_and_set_1:
268   case Builtin::BI__sync_lock_test_and_set_2:
269   case Builtin::BI__sync_lock_test_and_set_4:
270   case Builtin::BI__sync_lock_test_and_set_8:
271   case Builtin::BI__sync_lock_test_and_set_16:
272   case Builtin::BI__sync_lock_release:
273   case Builtin::BI__sync_lock_release_1:
274   case Builtin::BI__sync_lock_release_2:
275   case Builtin::BI__sync_lock_release_4:
276   case Builtin::BI__sync_lock_release_8:
277   case Builtin::BI__sync_lock_release_16:
278   case Builtin::BI__sync_swap:
279   case Builtin::BI__sync_swap_1:
280   case Builtin::BI__sync_swap_2:
281   case Builtin::BI__sync_swap_4:
282   case Builtin::BI__sync_swap_8:
283   case Builtin::BI__sync_swap_16:
284     return SemaBuiltinAtomicOverloaded(TheCallResult);
285 #define BUILTIN(ID, TYPE, ATTRS)
286 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287   case Builtin::BI##ID: \
288     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289 #include "clang/Basic/Builtins.def"
290   case Builtin::BI__builtin_annotation:
291     if (SemaBuiltinAnnotation(*this, TheCall))
292       return ExprError();
293     break;
294   case Builtin::BI__builtin_addressof:
295     if (SemaBuiltinAddressof(*this, TheCall))
296       return ExprError();
297     break;
298   }
299 
300   // Since the target specific builtins for each arch overlap, only check those
301   // of the arch we are compiling for.
302   if (BuiltinID >= Builtin::FirstTSBuiltin) {
303     switch (Context.getTargetInfo().getTriple().getArch()) {
304       case llvm::Triple::arm:
305       case llvm::Triple::thumb:
306         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307           return ExprError();
308         break;
309       case llvm::Triple::aarch64:
310       case llvm::Triple::aarch64_be:
311         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
312           return ExprError();
313         break;
314       case llvm::Triple::mips:
315       case llvm::Triple::mipsel:
316       case llvm::Triple::mips64:
317       case llvm::Triple::mips64el:
318         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
319           return ExprError();
320         break;
321       case llvm::Triple::x86:
322       case llvm::Triple::x86_64:
323         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
324           return ExprError();
325         break;
326       default:
327         break;
328     }
329   }
330 
331   return TheCallResult;
332 }
333 
334 // Get the valid immediate range for the specified NEON type code.
335 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
336   NeonTypeFlags Type(t);
337   int IsQuad = ForceQuad ? true : Type.isQuad();
338   switch (Type.getEltType()) {
339   case NeonTypeFlags::Int8:
340   case NeonTypeFlags::Poly8:
341     return shift ? 7 : (8 << IsQuad) - 1;
342   case NeonTypeFlags::Int16:
343   case NeonTypeFlags::Poly16:
344     return shift ? 15 : (4 << IsQuad) - 1;
345   case NeonTypeFlags::Int32:
346     return shift ? 31 : (2 << IsQuad) - 1;
347   case NeonTypeFlags::Int64:
348   case NeonTypeFlags::Poly64:
349     return shift ? 63 : (1 << IsQuad) - 1;
350   case NeonTypeFlags::Poly128:
351     return shift ? 127 : (1 << IsQuad) - 1;
352   case NeonTypeFlags::Float16:
353     assert(!shift && "cannot shift float types!");
354     return (4 << IsQuad) - 1;
355   case NeonTypeFlags::Float32:
356     assert(!shift && "cannot shift float types!");
357     return (2 << IsQuad) - 1;
358   case NeonTypeFlags::Float64:
359     assert(!shift && "cannot shift float types!");
360     return (1 << IsQuad) - 1;
361   }
362   llvm_unreachable("Invalid NeonTypeFlag!");
363 }
364 
365 /// getNeonEltType - Return the QualType corresponding to the elements of
366 /// the vector type specified by the NeonTypeFlags.  This is used to check
367 /// the pointer arguments for Neon load/store intrinsics.
368 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
369                                bool IsAArch64) {
370   switch (Flags.getEltType()) {
371   case NeonTypeFlags::Int8:
372     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
373   case NeonTypeFlags::Int16:
374     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
375   case NeonTypeFlags::Int32:
376     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
377   case NeonTypeFlags::Int64:
378     if (IsAArch64)
379       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
380     else
381       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
382                                 : Context.LongLongTy;
383   case NeonTypeFlags::Poly8:
384     return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
385   case NeonTypeFlags::Poly16:
386     return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
387   case NeonTypeFlags::Poly64:
388     return Context.UnsignedLongTy;
389   case NeonTypeFlags::Poly128:
390     break;
391   case NeonTypeFlags::Float16:
392     return Context.HalfTy;
393   case NeonTypeFlags::Float32:
394     return Context.FloatTy;
395   case NeonTypeFlags::Float64:
396     return Context.DoubleTy;
397   }
398   llvm_unreachable("Invalid NeonTypeFlag!");
399 }
400 
401 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
402   llvm::APSInt Result;
403   uint64_t mask = 0;
404   unsigned TV = 0;
405   int PtrArgNum = -1;
406   bool HasConstPtr = false;
407   switch (BuiltinID) {
408 #define GET_NEON_OVERLOAD_CHECK
409 #include "clang/Basic/arm_neon.inc"
410 #undef GET_NEON_OVERLOAD_CHECK
411   }
412 
413   // For NEON intrinsics which are overloaded on vector element type, validate
414   // the immediate which specifies which variant to emit.
415   unsigned ImmArg = TheCall->getNumArgs()-1;
416   if (mask) {
417     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
418       return true;
419 
420     TV = Result.getLimitedValue(64);
421     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
422       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
423         << TheCall->getArg(ImmArg)->getSourceRange();
424   }
425 
426   if (PtrArgNum >= 0) {
427     // Check that pointer arguments have the specified type.
428     Expr *Arg = TheCall->getArg(PtrArgNum);
429     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
430       Arg = ICE->getSubExpr();
431     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
432     QualType RHSTy = RHS.get()->getType();
433 
434     bool IsAArch64 =
435         Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
436     QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
437     if (HasConstPtr)
438       EltTy = EltTy.withConst();
439     QualType LHSTy = Context.getPointerType(EltTy);
440     AssignConvertType ConvTy;
441     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
442     if (RHS.isInvalid())
443       return true;
444     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
445                                  RHS.get(), AA_Assigning))
446       return true;
447   }
448 
449   // For NEON intrinsics which take an immediate value as part of the
450   // instruction, range check them here.
451   unsigned i = 0, l = 0, u = 0;
452   switch (BuiltinID) {
453   default:
454     return false;
455 #define GET_NEON_IMMEDIATE_CHECK
456 #include "clang/Basic/arm_neon.inc"
457 #undef GET_NEON_IMMEDIATE_CHECK
458   }
459   ;
460 
461   // We can't check the value of a dependent argument.
462   if (TheCall->getArg(i)->isTypeDependent() ||
463       TheCall->getArg(i)->isValueDependent())
464     return false;
465 
466   // Check that the immediate argument is actually a constant.
467   if (SemaBuiltinConstantArg(TheCall, i, Result))
468     return true;
469 
470   // Range check against the upper/lower values for this isntruction.
471   unsigned Val = Result.getZExtValue();
472   if (Val < l || Val > (u + l))
473     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
474            << l << u + l << TheCall->getArg(i)->getSourceRange();
475 
476   return false;
477 }
478 
479 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
480                                            CallExpr *TheCall) {
481   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
482     return true;
483 
484   return false;
485 }
486 
487 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
488   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
489           BuiltinID == ARM::BI__builtin_arm_strex) &&
490          "unexpected ARM builtin");
491   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
492 
493   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
494 
495   // Ensure that we have the proper number of arguments.
496   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
497     return true;
498 
499   // Inspect the pointer argument of the atomic builtin.  This should always be
500   // a pointer type, whose element is an integral scalar or pointer type.
501   // Because it is a pointer type, we don't have to worry about any implicit
502   // casts here.
503   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
504   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
505   if (PointerArgRes.isInvalid())
506     return true;
507   PointerArg = PointerArgRes.take();
508 
509   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
510   if (!pointerType) {
511     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
512       << PointerArg->getType() << PointerArg->getSourceRange();
513     return true;
514   }
515 
516   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
517   // task is to insert the appropriate casts into the AST. First work out just
518   // what the appropriate type is.
519   QualType ValType = pointerType->getPointeeType();
520   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
521   if (IsLdrex)
522     AddrType.addConst();
523 
524   // Issue a warning if the cast is dodgy.
525   CastKind CastNeeded = CK_NoOp;
526   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
527     CastNeeded = CK_BitCast;
528     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
529       << PointerArg->getType()
530       << Context.getPointerType(AddrType)
531       << AA_Passing << PointerArg->getSourceRange();
532   }
533 
534   // Finally, do the cast and replace the argument with the corrected version.
535   AddrType = Context.getPointerType(AddrType);
536   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
537   if (PointerArgRes.isInvalid())
538     return true;
539   PointerArg = PointerArgRes.take();
540 
541   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
542 
543   // In general, we allow ints, floats and pointers to be loaded and stored.
544   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
545       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
546     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
547       << PointerArg->getType() << PointerArg->getSourceRange();
548     return true;
549   }
550 
551   // But ARM doesn't have instructions to deal with 128-bit versions.
552   if (Context.getTypeSize(ValType) > 64) {
553     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
554       << PointerArg->getType() << PointerArg->getSourceRange();
555     return true;
556   }
557 
558   switch (ValType.getObjCLifetime()) {
559   case Qualifiers::OCL_None:
560   case Qualifiers::OCL_ExplicitNone:
561     // okay
562     break;
563 
564   case Qualifiers::OCL_Weak:
565   case Qualifiers::OCL_Strong:
566   case Qualifiers::OCL_Autoreleasing:
567     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
568       << ValType << PointerArg->getSourceRange();
569     return true;
570   }
571 
572 
573   if (IsLdrex) {
574     TheCall->setType(ValType);
575     return false;
576   }
577 
578   // Initialize the argument to be stored.
579   ExprResult ValArg = TheCall->getArg(0);
580   InitializedEntity Entity = InitializedEntity::InitializeParameter(
581       Context, ValType, /*consume*/ false);
582   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
583   if (ValArg.isInvalid())
584     return true;
585   TheCall->setArg(0, ValArg.get());
586 
587   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
588   // but the custom checker bypasses all default analysis.
589   TheCall->setType(Context.IntTy);
590   return false;
591 }
592 
593 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
594   llvm::APSInt Result;
595 
596   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
597       BuiltinID == ARM::BI__builtin_arm_strex) {
598     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
599   }
600 
601   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
602     return true;
603 
604   // For NEON intrinsics which take an immediate value as part of the
605   // instruction, range check them here.
606   unsigned i = 0, l = 0, u = 0;
607   switch (BuiltinID) {
608   default: return false;
609   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
610   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
611   case ARM::BI__builtin_arm_vcvtr_f:
612   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
613   case ARM::BI__builtin_arm_dmb:
614   case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
615   };
616 
617   // We can't check the value of a dependent argument.
618   if (TheCall->getArg(i)->isTypeDependent() ||
619       TheCall->getArg(i)->isValueDependent())
620     return false;
621 
622   // Check that the immediate argument is actually a constant.
623   if (SemaBuiltinConstantArg(TheCall, i, Result))
624     return true;
625 
626   // Range check against the upper/lower values for this isntruction.
627   unsigned Val = Result.getZExtValue();
628   if (Val < l || Val > (u + l))
629     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
630       << l << u+l << TheCall->getArg(i)->getSourceRange();
631 
632   // FIXME: VFP Intrinsics should error if VFP not present.
633   return false;
634 }
635 
636 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
637   unsigned i = 0, l = 0, u = 0;
638   switch (BuiltinID) {
639   default: return false;
640   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
641   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
642   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
643   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
644   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
645   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
646   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
647   };
648 
649   // We can't check the value of a dependent argument.
650   if (TheCall->getArg(i)->isTypeDependent() ||
651       TheCall->getArg(i)->isValueDependent())
652     return false;
653 
654   // Check that the immediate argument is actually a constant.
655   llvm::APSInt Result;
656   if (SemaBuiltinConstantArg(TheCall, i, Result))
657     return true;
658 
659   // Range check against the upper/lower values for this instruction.
660   unsigned Val = Result.getZExtValue();
661   if (Val < l || Val > u)
662     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
663       << l << u << TheCall->getArg(i)->getSourceRange();
664 
665   return false;
666 }
667 
668 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
669   switch (BuiltinID) {
670   case X86::BI_mm_prefetch:
671     return SemaBuiltinMMPrefetch(TheCall);
672   }
673   return false;
674 }
675 
676 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
677 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
678 /// Returns true when the format fits the function and the FormatStringInfo has
679 /// been populated.
680 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
681                                FormatStringInfo *FSI) {
682   FSI->HasVAListArg = Format->getFirstArg() == 0;
683   FSI->FormatIdx = Format->getFormatIdx() - 1;
684   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
685 
686   // The way the format attribute works in GCC, the implicit this argument
687   // of member functions is counted. However, it doesn't appear in our own
688   // lists, so decrement format_idx in that case.
689   if (IsCXXMember) {
690     if(FSI->FormatIdx == 0)
691       return false;
692     --FSI->FormatIdx;
693     if (FSI->FirstDataArg != 0)
694       --FSI->FirstDataArg;
695   }
696   return true;
697 }
698 
699 /// Checks if a the given expression evaluates to null.
700 ///
701 /// \brief Returns true if the value evaluates to null.
702 static bool CheckNonNullExpr(Sema &S,
703                              const Expr *Expr) {
704   // As a special case, transparent unions initialized with zero are
705   // considered null for the purposes of the nonnull attribute.
706   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
707     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
708       if (const CompoundLiteralExpr *CLE =
709           dyn_cast<CompoundLiteralExpr>(Expr))
710         if (const InitListExpr *ILE =
711             dyn_cast<InitListExpr>(CLE->getInitializer()))
712           Expr = ILE->getInit(0);
713   }
714 
715   bool Result;
716   return (!Expr->isValueDependent() &&
717           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
718           !Result);
719 }
720 
721 static void CheckNonNullArgument(Sema &S,
722                                  const Expr *ArgExpr,
723                                  SourceLocation CallSiteLoc) {
724   if (CheckNonNullExpr(S, ArgExpr))
725     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
726 }
727 
728 static void CheckNonNullArguments(Sema &S,
729                                   const NamedDecl *FDecl,
730                                   const Expr * const *ExprArgs,
731                                   SourceLocation CallSiteLoc) {
732   // Check the attributes attached to the method/function itself.
733   for (specific_attr_iterator<NonNullAttr>
734        I = FDecl->specific_attr_begin<NonNullAttr>(),
735        E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
736 
737     const NonNullAttr *NonNull = *I;
738     for (NonNullAttr::args_iterator i = NonNull->args_begin(),
739          e = NonNull->args_end();
740          i != e; ++i) {
741       CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
742     }
743   }
744 
745   // Check the attributes on the parameters.
746   ArrayRef<ParmVarDecl*> parms;
747   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
748     parms = FD->parameters();
749   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
750     parms = MD->parameters();
751 
752   unsigned argIndex = 0;
753   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
754        I != E; ++I, ++argIndex) {
755     const ParmVarDecl *PVD = *I;
756     if (PVD->hasAttr<NonNullAttr>())
757       CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
758   }
759 }
760 
761 /// Handles the checks for format strings, non-POD arguments to vararg
762 /// functions, and NULL arguments passed to non-NULL parameters.
763 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
764                      unsigned NumParams, bool IsMemberFunction,
765                      SourceLocation Loc, SourceRange Range,
766                      VariadicCallType CallType) {
767   // FIXME: We should check as much as we can in the template definition.
768   if (CurContext->isDependentContext())
769     return;
770 
771   // Printf and scanf checking.
772   llvm::SmallBitVector CheckedVarArgs;
773   if (FDecl) {
774     for (specific_attr_iterator<FormatAttr>
775              I = FDecl->specific_attr_begin<FormatAttr>(),
776              E = FDecl->specific_attr_end<FormatAttr>();
777          I != E; ++I) {
778       // Only create vector if there are format attributes.
779       CheckedVarArgs.resize(Args.size());
780 
781       CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
782                            CheckedVarArgs);
783     }
784   }
785 
786   // Refuse POD arguments that weren't caught by the format string
787   // checks above.
788   if (CallType != VariadicDoesNotApply) {
789     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
790       // Args[ArgIdx] can be null in malformed code.
791       if (const Expr *Arg = Args[ArgIdx]) {
792         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
793           checkVariadicArgument(Arg, CallType);
794       }
795     }
796   }
797 
798   if (FDecl) {
799     CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
800 
801     // Type safety checking.
802     for (specific_attr_iterator<ArgumentWithTypeTagAttr>
803            i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
804            e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
805          i != e; ++i) {
806       CheckArgumentWithTypeTag(*i, Args.data());
807     }
808   }
809 }
810 
811 /// CheckConstructorCall - Check a constructor call for correctness and safety
812 /// properties not enforced by the C type system.
813 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
814                                 ArrayRef<const Expr *> Args,
815                                 const FunctionProtoType *Proto,
816                                 SourceLocation Loc) {
817   VariadicCallType CallType =
818     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
819   checkCall(FDecl, Args, Proto->getNumParams(),
820             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
821 }
822 
823 /// CheckFunctionCall - Check a direct function call for various correctness
824 /// and safety properties not strictly enforced by the C type system.
825 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
826                              const FunctionProtoType *Proto) {
827   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
828                               isa<CXXMethodDecl>(FDecl);
829   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
830                           IsMemberOperatorCall;
831   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
832                                                   TheCall->getCallee());
833   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
834   Expr** Args = TheCall->getArgs();
835   unsigned NumArgs = TheCall->getNumArgs();
836   if (IsMemberOperatorCall) {
837     // If this is a call to a member operator, hide the first argument
838     // from checkCall.
839     // FIXME: Our choice of AST representation here is less than ideal.
840     ++Args;
841     --NumArgs;
842   }
843   checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
844             IsMemberFunction, TheCall->getRParenLoc(),
845             TheCall->getCallee()->getSourceRange(), CallType);
846 
847   IdentifierInfo *FnInfo = FDecl->getIdentifier();
848   // None of the checks below are needed for functions that don't have
849   // simple names (e.g., C++ conversion functions).
850   if (!FnInfo)
851     return false;
852 
853   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
854 
855   unsigned CMId = FDecl->getMemoryFunctionKind();
856   if (CMId == 0)
857     return false;
858 
859   // Handle memory setting and copying functions.
860   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
861     CheckStrlcpycatArguments(TheCall, FnInfo);
862   else if (CMId == Builtin::BIstrncat)
863     CheckStrncatArguments(TheCall, FnInfo);
864   else
865     CheckMemaccessArguments(TheCall, CMId, FnInfo);
866 
867   return false;
868 }
869 
870 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
871                                ArrayRef<const Expr *> Args) {
872   VariadicCallType CallType =
873       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
874 
875   checkCall(Method, Args, Method->param_size(),
876             /*IsMemberFunction=*/false,
877             lbrac, Method->getSourceRange(), CallType);
878 
879   return false;
880 }
881 
882 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
883                             const FunctionProtoType *Proto) {
884   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
885   if (!V)
886     return false;
887 
888   QualType Ty = V->getType();
889   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
890     return false;
891 
892   VariadicCallType CallType;
893   if (!Proto || !Proto->isVariadic()) {
894     CallType = VariadicDoesNotApply;
895   } else if (Ty->isBlockPointerType()) {
896     CallType = VariadicBlock;
897   } else { // Ty->isFunctionPointerType()
898     CallType = VariadicFunction;
899   }
900   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
901 
902   checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
903                                                     TheCall->getNumArgs()),
904             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
905             TheCall->getCallee()->getSourceRange(), CallType);
906 
907   return false;
908 }
909 
910 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
911 /// such as function pointers returned from functions.
912 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
913   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
914                                                   TheCall->getCallee());
915   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
916 
917   checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
918                              TheCall->getArgs(), TheCall->getNumArgs()),
919             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
920             TheCall->getCallee()->getSourceRange(), CallType);
921 
922   return false;
923 }
924 
925 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
926                                          AtomicExpr::AtomicOp Op) {
927   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
928   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
929 
930   // All these operations take one of the following forms:
931   enum {
932     // C    __c11_atomic_init(A *, C)
933     Init,
934     // C    __c11_atomic_load(A *, int)
935     Load,
936     // void __atomic_load(A *, CP, int)
937     Copy,
938     // C    __c11_atomic_add(A *, M, int)
939     Arithmetic,
940     // C    __atomic_exchange_n(A *, CP, int)
941     Xchg,
942     // void __atomic_exchange(A *, C *, CP, int)
943     GNUXchg,
944     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
945     C11CmpXchg,
946     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
947     GNUCmpXchg
948   } Form = Init;
949   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
950   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
951   // where:
952   //   C is an appropriate type,
953   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
954   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
955   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
956   //   the int parameters are for orderings.
957 
958   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
959          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
960          && "need to update code for modified C11 atomics");
961   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
962                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
963   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
964              Op == AtomicExpr::AO__atomic_store_n ||
965              Op == AtomicExpr::AO__atomic_exchange_n ||
966              Op == AtomicExpr::AO__atomic_compare_exchange_n;
967   bool IsAddSub = false;
968 
969   switch (Op) {
970   case AtomicExpr::AO__c11_atomic_init:
971     Form = Init;
972     break;
973 
974   case AtomicExpr::AO__c11_atomic_load:
975   case AtomicExpr::AO__atomic_load_n:
976     Form = Load;
977     break;
978 
979   case AtomicExpr::AO__c11_atomic_store:
980   case AtomicExpr::AO__atomic_load:
981   case AtomicExpr::AO__atomic_store:
982   case AtomicExpr::AO__atomic_store_n:
983     Form = Copy;
984     break;
985 
986   case AtomicExpr::AO__c11_atomic_fetch_add:
987   case AtomicExpr::AO__c11_atomic_fetch_sub:
988   case AtomicExpr::AO__atomic_fetch_add:
989   case AtomicExpr::AO__atomic_fetch_sub:
990   case AtomicExpr::AO__atomic_add_fetch:
991   case AtomicExpr::AO__atomic_sub_fetch:
992     IsAddSub = true;
993     // Fall through.
994   case AtomicExpr::AO__c11_atomic_fetch_and:
995   case AtomicExpr::AO__c11_atomic_fetch_or:
996   case AtomicExpr::AO__c11_atomic_fetch_xor:
997   case AtomicExpr::AO__atomic_fetch_and:
998   case AtomicExpr::AO__atomic_fetch_or:
999   case AtomicExpr::AO__atomic_fetch_xor:
1000   case AtomicExpr::AO__atomic_fetch_nand:
1001   case AtomicExpr::AO__atomic_and_fetch:
1002   case AtomicExpr::AO__atomic_or_fetch:
1003   case AtomicExpr::AO__atomic_xor_fetch:
1004   case AtomicExpr::AO__atomic_nand_fetch:
1005     Form = Arithmetic;
1006     break;
1007 
1008   case AtomicExpr::AO__c11_atomic_exchange:
1009   case AtomicExpr::AO__atomic_exchange_n:
1010     Form = Xchg;
1011     break;
1012 
1013   case AtomicExpr::AO__atomic_exchange:
1014     Form = GNUXchg;
1015     break;
1016 
1017   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1018   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1019     Form = C11CmpXchg;
1020     break;
1021 
1022   case AtomicExpr::AO__atomic_compare_exchange:
1023   case AtomicExpr::AO__atomic_compare_exchange_n:
1024     Form = GNUCmpXchg;
1025     break;
1026   }
1027 
1028   // Check we have the right number of arguments.
1029   if (TheCall->getNumArgs() < NumArgs[Form]) {
1030     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1031       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1032       << TheCall->getCallee()->getSourceRange();
1033     return ExprError();
1034   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1035     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1036          diag::err_typecheck_call_too_many_args)
1037       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1038       << TheCall->getCallee()->getSourceRange();
1039     return ExprError();
1040   }
1041 
1042   // Inspect the first argument of the atomic operation.
1043   Expr *Ptr = TheCall->getArg(0);
1044   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1045   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1046   if (!pointerType) {
1047     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1048       << Ptr->getType() << Ptr->getSourceRange();
1049     return ExprError();
1050   }
1051 
1052   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1053   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1054   QualType ValType = AtomTy; // 'C'
1055   if (IsC11) {
1056     if (!AtomTy->isAtomicType()) {
1057       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1058         << Ptr->getType() << Ptr->getSourceRange();
1059       return ExprError();
1060     }
1061     if (AtomTy.isConstQualified()) {
1062       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1063         << Ptr->getType() << Ptr->getSourceRange();
1064       return ExprError();
1065     }
1066     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1067   }
1068 
1069   // For an arithmetic operation, the implied arithmetic must be well-formed.
1070   if (Form == Arithmetic) {
1071     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1072     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1073       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1074         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1075       return ExprError();
1076     }
1077     if (!IsAddSub && !ValType->isIntegerType()) {
1078       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1079         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1080       return ExprError();
1081     }
1082   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1083     // For __atomic_*_n operations, the value type must be a scalar integral or
1084     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1085     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1086       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1087     return ExprError();
1088   }
1089 
1090   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1091       !AtomTy->isScalarType()) {
1092     // For GNU atomics, require a trivially-copyable type. This is not part of
1093     // the GNU atomics specification, but we enforce it for sanity.
1094     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1095       << Ptr->getType() << Ptr->getSourceRange();
1096     return ExprError();
1097   }
1098 
1099   // FIXME: For any builtin other than a load, the ValType must not be
1100   // const-qualified.
1101 
1102   switch (ValType.getObjCLifetime()) {
1103   case Qualifiers::OCL_None:
1104   case Qualifiers::OCL_ExplicitNone:
1105     // okay
1106     break;
1107 
1108   case Qualifiers::OCL_Weak:
1109   case Qualifiers::OCL_Strong:
1110   case Qualifiers::OCL_Autoreleasing:
1111     // FIXME: Can this happen? By this point, ValType should be known
1112     // to be trivially copyable.
1113     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1114       << ValType << Ptr->getSourceRange();
1115     return ExprError();
1116   }
1117 
1118   QualType ResultType = ValType;
1119   if (Form == Copy || Form == GNUXchg || Form == Init)
1120     ResultType = Context.VoidTy;
1121   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1122     ResultType = Context.BoolTy;
1123 
1124   // The type of a parameter passed 'by value'. In the GNU atomics, such
1125   // arguments are actually passed as pointers.
1126   QualType ByValType = ValType; // 'CP'
1127   if (!IsC11 && !IsN)
1128     ByValType = Ptr->getType();
1129 
1130   // The first argument --- the pointer --- has a fixed type; we
1131   // deduce the types of the rest of the arguments accordingly.  Walk
1132   // the remaining arguments, converting them to the deduced value type.
1133   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1134     QualType Ty;
1135     if (i < NumVals[Form] + 1) {
1136       switch (i) {
1137       case 1:
1138         // The second argument is the non-atomic operand. For arithmetic, this
1139         // is always passed by value, and for a compare_exchange it is always
1140         // passed by address. For the rest, GNU uses by-address and C11 uses
1141         // by-value.
1142         assert(Form != Load);
1143         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1144           Ty = ValType;
1145         else if (Form == Copy || Form == Xchg)
1146           Ty = ByValType;
1147         else if (Form == Arithmetic)
1148           Ty = Context.getPointerDiffType();
1149         else
1150           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1151         break;
1152       case 2:
1153         // The third argument to compare_exchange / GNU exchange is a
1154         // (pointer to a) desired value.
1155         Ty = ByValType;
1156         break;
1157       case 3:
1158         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1159         Ty = Context.BoolTy;
1160         break;
1161       }
1162     } else {
1163       // The order(s) are always converted to int.
1164       Ty = Context.IntTy;
1165     }
1166 
1167     InitializedEntity Entity =
1168         InitializedEntity::InitializeParameter(Context, Ty, false);
1169     ExprResult Arg = TheCall->getArg(i);
1170     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1171     if (Arg.isInvalid())
1172       return true;
1173     TheCall->setArg(i, Arg.get());
1174   }
1175 
1176   // Permute the arguments into a 'consistent' order.
1177   SmallVector<Expr*, 5> SubExprs;
1178   SubExprs.push_back(Ptr);
1179   switch (Form) {
1180   case Init:
1181     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1182     SubExprs.push_back(TheCall->getArg(1)); // Val1
1183     break;
1184   case Load:
1185     SubExprs.push_back(TheCall->getArg(1)); // Order
1186     break;
1187   case Copy:
1188   case Arithmetic:
1189   case Xchg:
1190     SubExprs.push_back(TheCall->getArg(2)); // Order
1191     SubExprs.push_back(TheCall->getArg(1)); // Val1
1192     break;
1193   case GNUXchg:
1194     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1195     SubExprs.push_back(TheCall->getArg(3)); // Order
1196     SubExprs.push_back(TheCall->getArg(1)); // Val1
1197     SubExprs.push_back(TheCall->getArg(2)); // Val2
1198     break;
1199   case C11CmpXchg:
1200     SubExprs.push_back(TheCall->getArg(3)); // Order
1201     SubExprs.push_back(TheCall->getArg(1)); // Val1
1202     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1203     SubExprs.push_back(TheCall->getArg(2)); // Val2
1204     break;
1205   case GNUCmpXchg:
1206     SubExprs.push_back(TheCall->getArg(4)); // Order
1207     SubExprs.push_back(TheCall->getArg(1)); // Val1
1208     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1209     SubExprs.push_back(TheCall->getArg(2)); // Val2
1210     SubExprs.push_back(TheCall->getArg(3)); // Weak
1211     break;
1212   }
1213 
1214   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1215                                             SubExprs, ResultType, Op,
1216                                             TheCall->getRParenLoc());
1217 
1218   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1219        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1220       Context.AtomicUsesUnsupportedLibcall(AE))
1221     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1222     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1223 
1224   return Owned(AE);
1225 }
1226 
1227 
1228 /// checkBuiltinArgument - Given a call to a builtin function, perform
1229 /// normal type-checking on the given argument, updating the call in
1230 /// place.  This is useful when a builtin function requires custom
1231 /// type-checking for some of its arguments but not necessarily all of
1232 /// them.
1233 ///
1234 /// Returns true on error.
1235 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1236   FunctionDecl *Fn = E->getDirectCallee();
1237   assert(Fn && "builtin call without direct callee!");
1238 
1239   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1240   InitializedEntity Entity =
1241     InitializedEntity::InitializeParameter(S.Context, Param);
1242 
1243   ExprResult Arg = E->getArg(0);
1244   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1245   if (Arg.isInvalid())
1246     return true;
1247 
1248   E->setArg(ArgIndex, Arg.take());
1249   return false;
1250 }
1251 
1252 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1253 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1254 /// type of its first argument.  The main ActOnCallExpr routines have already
1255 /// promoted the types of arguments because all of these calls are prototyped as
1256 /// void(...).
1257 ///
1258 /// This function goes through and does final semantic checking for these
1259 /// builtins,
1260 ExprResult
1261 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1262   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1263   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1264   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1265 
1266   // Ensure that we have at least one argument to do type inference from.
1267   if (TheCall->getNumArgs() < 1) {
1268     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1269       << 0 << 1 << TheCall->getNumArgs()
1270       << TheCall->getCallee()->getSourceRange();
1271     return ExprError();
1272   }
1273 
1274   // Inspect the first argument of the atomic builtin.  This should always be
1275   // a pointer type, whose element is an integral scalar or pointer type.
1276   // Because it is a pointer type, we don't have to worry about any implicit
1277   // casts here.
1278   // FIXME: We don't allow floating point scalars as input.
1279   Expr *FirstArg = TheCall->getArg(0);
1280   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1281   if (FirstArgResult.isInvalid())
1282     return ExprError();
1283   FirstArg = FirstArgResult.take();
1284   TheCall->setArg(0, FirstArg);
1285 
1286   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1287   if (!pointerType) {
1288     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1289       << FirstArg->getType() << FirstArg->getSourceRange();
1290     return ExprError();
1291   }
1292 
1293   QualType ValType = pointerType->getPointeeType();
1294   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1295       !ValType->isBlockPointerType()) {
1296     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1297       << FirstArg->getType() << FirstArg->getSourceRange();
1298     return ExprError();
1299   }
1300 
1301   switch (ValType.getObjCLifetime()) {
1302   case Qualifiers::OCL_None:
1303   case Qualifiers::OCL_ExplicitNone:
1304     // okay
1305     break;
1306 
1307   case Qualifiers::OCL_Weak:
1308   case Qualifiers::OCL_Strong:
1309   case Qualifiers::OCL_Autoreleasing:
1310     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1311       << ValType << FirstArg->getSourceRange();
1312     return ExprError();
1313   }
1314 
1315   // Strip any qualifiers off ValType.
1316   ValType = ValType.getUnqualifiedType();
1317 
1318   // The majority of builtins return a value, but a few have special return
1319   // types, so allow them to override appropriately below.
1320   QualType ResultType = ValType;
1321 
1322   // We need to figure out which concrete builtin this maps onto.  For example,
1323   // __sync_fetch_and_add with a 2 byte object turns into
1324   // __sync_fetch_and_add_2.
1325 #define BUILTIN_ROW(x) \
1326   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1327     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1328 
1329   static const unsigned BuiltinIndices[][5] = {
1330     BUILTIN_ROW(__sync_fetch_and_add),
1331     BUILTIN_ROW(__sync_fetch_and_sub),
1332     BUILTIN_ROW(__sync_fetch_and_or),
1333     BUILTIN_ROW(__sync_fetch_and_and),
1334     BUILTIN_ROW(__sync_fetch_and_xor),
1335 
1336     BUILTIN_ROW(__sync_add_and_fetch),
1337     BUILTIN_ROW(__sync_sub_and_fetch),
1338     BUILTIN_ROW(__sync_and_and_fetch),
1339     BUILTIN_ROW(__sync_or_and_fetch),
1340     BUILTIN_ROW(__sync_xor_and_fetch),
1341 
1342     BUILTIN_ROW(__sync_val_compare_and_swap),
1343     BUILTIN_ROW(__sync_bool_compare_and_swap),
1344     BUILTIN_ROW(__sync_lock_test_and_set),
1345     BUILTIN_ROW(__sync_lock_release),
1346     BUILTIN_ROW(__sync_swap)
1347   };
1348 #undef BUILTIN_ROW
1349 
1350   // Determine the index of the size.
1351   unsigned SizeIndex;
1352   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1353   case 1: SizeIndex = 0; break;
1354   case 2: SizeIndex = 1; break;
1355   case 4: SizeIndex = 2; break;
1356   case 8: SizeIndex = 3; break;
1357   case 16: SizeIndex = 4; break;
1358   default:
1359     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1360       << FirstArg->getType() << FirstArg->getSourceRange();
1361     return ExprError();
1362   }
1363 
1364   // Each of these builtins has one pointer argument, followed by some number of
1365   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1366   // that we ignore.  Find out which row of BuiltinIndices to read from as well
1367   // as the number of fixed args.
1368   unsigned BuiltinID = FDecl->getBuiltinID();
1369   unsigned BuiltinIndex, NumFixed = 1;
1370   switch (BuiltinID) {
1371   default: llvm_unreachable("Unknown overloaded atomic builtin!");
1372   case Builtin::BI__sync_fetch_and_add:
1373   case Builtin::BI__sync_fetch_and_add_1:
1374   case Builtin::BI__sync_fetch_and_add_2:
1375   case Builtin::BI__sync_fetch_and_add_4:
1376   case Builtin::BI__sync_fetch_and_add_8:
1377   case Builtin::BI__sync_fetch_and_add_16:
1378     BuiltinIndex = 0;
1379     break;
1380 
1381   case Builtin::BI__sync_fetch_and_sub:
1382   case Builtin::BI__sync_fetch_and_sub_1:
1383   case Builtin::BI__sync_fetch_and_sub_2:
1384   case Builtin::BI__sync_fetch_and_sub_4:
1385   case Builtin::BI__sync_fetch_and_sub_8:
1386   case Builtin::BI__sync_fetch_and_sub_16:
1387     BuiltinIndex = 1;
1388     break;
1389 
1390   case Builtin::BI__sync_fetch_and_or:
1391   case Builtin::BI__sync_fetch_and_or_1:
1392   case Builtin::BI__sync_fetch_and_or_2:
1393   case Builtin::BI__sync_fetch_and_or_4:
1394   case Builtin::BI__sync_fetch_and_or_8:
1395   case Builtin::BI__sync_fetch_and_or_16:
1396     BuiltinIndex = 2;
1397     break;
1398 
1399   case Builtin::BI__sync_fetch_and_and:
1400   case Builtin::BI__sync_fetch_and_and_1:
1401   case Builtin::BI__sync_fetch_and_and_2:
1402   case Builtin::BI__sync_fetch_and_and_4:
1403   case Builtin::BI__sync_fetch_and_and_8:
1404   case Builtin::BI__sync_fetch_and_and_16:
1405     BuiltinIndex = 3;
1406     break;
1407 
1408   case Builtin::BI__sync_fetch_and_xor:
1409   case Builtin::BI__sync_fetch_and_xor_1:
1410   case Builtin::BI__sync_fetch_and_xor_2:
1411   case Builtin::BI__sync_fetch_and_xor_4:
1412   case Builtin::BI__sync_fetch_and_xor_8:
1413   case Builtin::BI__sync_fetch_and_xor_16:
1414     BuiltinIndex = 4;
1415     break;
1416 
1417   case Builtin::BI__sync_add_and_fetch:
1418   case Builtin::BI__sync_add_and_fetch_1:
1419   case Builtin::BI__sync_add_and_fetch_2:
1420   case Builtin::BI__sync_add_and_fetch_4:
1421   case Builtin::BI__sync_add_and_fetch_8:
1422   case Builtin::BI__sync_add_and_fetch_16:
1423     BuiltinIndex = 5;
1424     break;
1425 
1426   case Builtin::BI__sync_sub_and_fetch:
1427   case Builtin::BI__sync_sub_and_fetch_1:
1428   case Builtin::BI__sync_sub_and_fetch_2:
1429   case Builtin::BI__sync_sub_and_fetch_4:
1430   case Builtin::BI__sync_sub_and_fetch_8:
1431   case Builtin::BI__sync_sub_and_fetch_16:
1432     BuiltinIndex = 6;
1433     break;
1434 
1435   case Builtin::BI__sync_and_and_fetch:
1436   case Builtin::BI__sync_and_and_fetch_1:
1437   case Builtin::BI__sync_and_and_fetch_2:
1438   case Builtin::BI__sync_and_and_fetch_4:
1439   case Builtin::BI__sync_and_and_fetch_8:
1440   case Builtin::BI__sync_and_and_fetch_16:
1441     BuiltinIndex = 7;
1442     break;
1443 
1444   case Builtin::BI__sync_or_and_fetch:
1445   case Builtin::BI__sync_or_and_fetch_1:
1446   case Builtin::BI__sync_or_and_fetch_2:
1447   case Builtin::BI__sync_or_and_fetch_4:
1448   case Builtin::BI__sync_or_and_fetch_8:
1449   case Builtin::BI__sync_or_and_fetch_16:
1450     BuiltinIndex = 8;
1451     break;
1452 
1453   case Builtin::BI__sync_xor_and_fetch:
1454   case Builtin::BI__sync_xor_and_fetch_1:
1455   case Builtin::BI__sync_xor_and_fetch_2:
1456   case Builtin::BI__sync_xor_and_fetch_4:
1457   case Builtin::BI__sync_xor_and_fetch_8:
1458   case Builtin::BI__sync_xor_and_fetch_16:
1459     BuiltinIndex = 9;
1460     break;
1461 
1462   case Builtin::BI__sync_val_compare_and_swap:
1463   case Builtin::BI__sync_val_compare_and_swap_1:
1464   case Builtin::BI__sync_val_compare_and_swap_2:
1465   case Builtin::BI__sync_val_compare_and_swap_4:
1466   case Builtin::BI__sync_val_compare_and_swap_8:
1467   case Builtin::BI__sync_val_compare_and_swap_16:
1468     BuiltinIndex = 10;
1469     NumFixed = 2;
1470     break;
1471 
1472   case Builtin::BI__sync_bool_compare_and_swap:
1473   case Builtin::BI__sync_bool_compare_and_swap_1:
1474   case Builtin::BI__sync_bool_compare_and_swap_2:
1475   case Builtin::BI__sync_bool_compare_and_swap_4:
1476   case Builtin::BI__sync_bool_compare_and_swap_8:
1477   case Builtin::BI__sync_bool_compare_and_swap_16:
1478     BuiltinIndex = 11;
1479     NumFixed = 2;
1480     ResultType = Context.BoolTy;
1481     break;
1482 
1483   case Builtin::BI__sync_lock_test_and_set:
1484   case Builtin::BI__sync_lock_test_and_set_1:
1485   case Builtin::BI__sync_lock_test_and_set_2:
1486   case Builtin::BI__sync_lock_test_and_set_4:
1487   case Builtin::BI__sync_lock_test_and_set_8:
1488   case Builtin::BI__sync_lock_test_and_set_16:
1489     BuiltinIndex = 12;
1490     break;
1491 
1492   case Builtin::BI__sync_lock_release:
1493   case Builtin::BI__sync_lock_release_1:
1494   case Builtin::BI__sync_lock_release_2:
1495   case Builtin::BI__sync_lock_release_4:
1496   case Builtin::BI__sync_lock_release_8:
1497   case Builtin::BI__sync_lock_release_16:
1498     BuiltinIndex = 13;
1499     NumFixed = 0;
1500     ResultType = Context.VoidTy;
1501     break;
1502 
1503   case Builtin::BI__sync_swap:
1504   case Builtin::BI__sync_swap_1:
1505   case Builtin::BI__sync_swap_2:
1506   case Builtin::BI__sync_swap_4:
1507   case Builtin::BI__sync_swap_8:
1508   case Builtin::BI__sync_swap_16:
1509     BuiltinIndex = 14;
1510     break;
1511   }
1512 
1513   // Now that we know how many fixed arguments we expect, first check that we
1514   // have at least that many.
1515   if (TheCall->getNumArgs() < 1+NumFixed) {
1516     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1517       << 0 << 1+NumFixed << TheCall->getNumArgs()
1518       << TheCall->getCallee()->getSourceRange();
1519     return ExprError();
1520   }
1521 
1522   // Get the decl for the concrete builtin from this, we can tell what the
1523   // concrete integer type we should convert to is.
1524   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1525   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1526   FunctionDecl *NewBuiltinDecl;
1527   if (NewBuiltinID == BuiltinID)
1528     NewBuiltinDecl = FDecl;
1529   else {
1530     // Perform builtin lookup to avoid redeclaring it.
1531     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1532     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1533     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1534     assert(Res.getFoundDecl());
1535     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1536     if (NewBuiltinDecl == 0)
1537       return ExprError();
1538   }
1539 
1540   // The first argument --- the pointer --- has a fixed type; we
1541   // deduce the types of the rest of the arguments accordingly.  Walk
1542   // the remaining arguments, converting them to the deduced value type.
1543   for (unsigned i = 0; i != NumFixed; ++i) {
1544     ExprResult Arg = TheCall->getArg(i+1);
1545 
1546     // GCC does an implicit conversion to the pointer or integer ValType.  This
1547     // can fail in some cases (1i -> int**), check for this error case now.
1548     // Initialize the argument.
1549     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1550                                                    ValType, /*consume*/ false);
1551     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1552     if (Arg.isInvalid())
1553       return ExprError();
1554 
1555     // Okay, we have something that *can* be converted to the right type.  Check
1556     // to see if there is a potentially weird extension going on here.  This can
1557     // happen when you do an atomic operation on something like an char* and
1558     // pass in 42.  The 42 gets converted to char.  This is even more strange
1559     // for things like 45.123 -> char, etc.
1560     // FIXME: Do this check.
1561     TheCall->setArg(i+1, Arg.take());
1562   }
1563 
1564   ASTContext& Context = this->getASTContext();
1565 
1566   // Create a new DeclRefExpr to refer to the new decl.
1567   DeclRefExpr* NewDRE = DeclRefExpr::Create(
1568       Context,
1569       DRE->getQualifierLoc(),
1570       SourceLocation(),
1571       NewBuiltinDecl,
1572       /*enclosing*/ false,
1573       DRE->getLocation(),
1574       Context.BuiltinFnTy,
1575       DRE->getValueKind());
1576 
1577   // Set the callee in the CallExpr.
1578   // FIXME: This loses syntactic information.
1579   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1580   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1581                                               CK_BuiltinFnToFnPtr);
1582   TheCall->setCallee(PromotedCall.take());
1583 
1584   // Change the result type of the call to match the original value type. This
1585   // is arbitrary, but the codegen for these builtins ins design to handle it
1586   // gracefully.
1587   TheCall->setType(ResultType);
1588 
1589   return TheCallResult;
1590 }
1591 
1592 /// CheckObjCString - Checks that the argument to the builtin
1593 /// CFString constructor is correct
1594 /// Note: It might also make sense to do the UTF-16 conversion here (would
1595 /// simplify the backend).
1596 bool Sema::CheckObjCString(Expr *Arg) {
1597   Arg = Arg->IgnoreParenCasts();
1598   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1599 
1600   if (!Literal || !Literal->isAscii()) {
1601     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1602       << Arg->getSourceRange();
1603     return true;
1604   }
1605 
1606   if (Literal->containsNonAsciiOrNull()) {
1607     StringRef String = Literal->getString();
1608     unsigned NumBytes = String.size();
1609     SmallVector<UTF16, 128> ToBuf(NumBytes);
1610     const UTF8 *FromPtr = (const UTF8 *)String.data();
1611     UTF16 *ToPtr = &ToBuf[0];
1612 
1613     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1614                                                  &ToPtr, ToPtr + NumBytes,
1615                                                  strictConversion);
1616     // Check for conversion failure.
1617     if (Result != conversionOK)
1618       Diag(Arg->getLocStart(),
1619            diag::warn_cfstring_truncated) << Arg->getSourceRange();
1620   }
1621   return false;
1622 }
1623 
1624 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1625 /// Emit an error and return true on failure, return false on success.
1626 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1627   Expr *Fn = TheCall->getCallee();
1628   if (TheCall->getNumArgs() > 2) {
1629     Diag(TheCall->getArg(2)->getLocStart(),
1630          diag::err_typecheck_call_too_many_args)
1631       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1632       << Fn->getSourceRange()
1633       << SourceRange(TheCall->getArg(2)->getLocStart(),
1634                      (*(TheCall->arg_end()-1))->getLocEnd());
1635     return true;
1636   }
1637 
1638   if (TheCall->getNumArgs() < 2) {
1639     return Diag(TheCall->getLocEnd(),
1640       diag::err_typecheck_call_too_few_args_at_least)
1641       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1642   }
1643 
1644   // Type-check the first argument normally.
1645   if (checkBuiltinArgument(*this, TheCall, 0))
1646     return true;
1647 
1648   // Determine whether the current function is variadic or not.
1649   BlockScopeInfo *CurBlock = getCurBlock();
1650   bool isVariadic;
1651   if (CurBlock)
1652     isVariadic = CurBlock->TheDecl->isVariadic();
1653   else if (FunctionDecl *FD = getCurFunctionDecl())
1654     isVariadic = FD->isVariadic();
1655   else
1656     isVariadic = getCurMethodDecl()->isVariadic();
1657 
1658   if (!isVariadic) {
1659     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1660     return true;
1661   }
1662 
1663   // Verify that the second argument to the builtin is the last argument of the
1664   // current function or method.
1665   bool SecondArgIsLastNamedArgument = false;
1666   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1667 
1668   // These are valid if SecondArgIsLastNamedArgument is false after the next
1669   // block.
1670   QualType Type;
1671   SourceLocation ParamLoc;
1672 
1673   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1674     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1675       // FIXME: This isn't correct for methods (results in bogus warning).
1676       // Get the last formal in the current function.
1677       const ParmVarDecl *LastArg;
1678       if (CurBlock)
1679         LastArg = *(CurBlock->TheDecl->param_end()-1);
1680       else if (FunctionDecl *FD = getCurFunctionDecl())
1681         LastArg = *(FD->param_end()-1);
1682       else
1683         LastArg = *(getCurMethodDecl()->param_end()-1);
1684       SecondArgIsLastNamedArgument = PV == LastArg;
1685 
1686       Type = PV->getType();
1687       ParamLoc = PV->getLocation();
1688     }
1689   }
1690 
1691   if (!SecondArgIsLastNamedArgument)
1692     Diag(TheCall->getArg(1)->getLocStart(),
1693          diag::warn_second_parameter_of_va_start_not_last_named_argument);
1694   else if (Type->isReferenceType()) {
1695     Diag(Arg->getLocStart(),
1696          diag::warn_va_start_of_reference_type_is_undefined);
1697     Diag(ParamLoc, diag::note_parameter_type) << Type;
1698   }
1699 
1700   TheCall->setType(Context.VoidTy);
1701   return false;
1702 }
1703 
1704 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1705 /// friends.  This is declared to take (...), so we have to check everything.
1706 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1707   if (TheCall->getNumArgs() < 2)
1708     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1709       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1710   if (TheCall->getNumArgs() > 2)
1711     return Diag(TheCall->getArg(2)->getLocStart(),
1712                 diag::err_typecheck_call_too_many_args)
1713       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1714       << SourceRange(TheCall->getArg(2)->getLocStart(),
1715                      (*(TheCall->arg_end()-1))->getLocEnd());
1716 
1717   ExprResult OrigArg0 = TheCall->getArg(0);
1718   ExprResult OrigArg1 = TheCall->getArg(1);
1719 
1720   // Do standard promotions between the two arguments, returning their common
1721   // type.
1722   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1723   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1724     return true;
1725 
1726   // Make sure any conversions are pushed back into the call; this is
1727   // type safe since unordered compare builtins are declared as "_Bool
1728   // foo(...)".
1729   TheCall->setArg(0, OrigArg0.get());
1730   TheCall->setArg(1, OrigArg1.get());
1731 
1732   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1733     return false;
1734 
1735   // If the common type isn't a real floating type, then the arguments were
1736   // invalid for this operation.
1737   if (Res.isNull() || !Res->isRealFloatingType())
1738     return Diag(OrigArg0.get()->getLocStart(),
1739                 diag::err_typecheck_call_invalid_ordered_compare)
1740       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1741       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1742 
1743   return false;
1744 }
1745 
1746 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1747 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1748 /// to check everything. We expect the last argument to be a floating point
1749 /// value.
1750 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1751   if (TheCall->getNumArgs() < NumArgs)
1752     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1753       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1754   if (TheCall->getNumArgs() > NumArgs)
1755     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1756                 diag::err_typecheck_call_too_many_args)
1757       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1758       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1759                      (*(TheCall->arg_end()-1))->getLocEnd());
1760 
1761   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1762 
1763   if (OrigArg->isTypeDependent())
1764     return false;
1765 
1766   // This operation requires a non-_Complex floating-point number.
1767   if (!OrigArg->getType()->isRealFloatingType())
1768     return Diag(OrigArg->getLocStart(),
1769                 diag::err_typecheck_call_invalid_unary_fp)
1770       << OrigArg->getType() << OrigArg->getSourceRange();
1771 
1772   // If this is an implicit conversion from float -> double, remove it.
1773   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1774     Expr *CastArg = Cast->getSubExpr();
1775     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1776       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1777              "promotion from float to double is the only expected cast here");
1778       Cast->setSubExpr(0);
1779       TheCall->setArg(NumArgs-1, CastArg);
1780     }
1781   }
1782 
1783   return false;
1784 }
1785 
1786 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1787 // This is declared to take (...), so we have to check everything.
1788 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1789   if (TheCall->getNumArgs() < 2)
1790     return ExprError(Diag(TheCall->getLocEnd(),
1791                           diag::err_typecheck_call_too_few_args_at_least)
1792                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1793                      << TheCall->getSourceRange());
1794 
1795   // Determine which of the following types of shufflevector we're checking:
1796   // 1) unary, vector mask: (lhs, mask)
1797   // 2) binary, vector mask: (lhs, rhs, mask)
1798   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1799   QualType resType = TheCall->getArg(0)->getType();
1800   unsigned numElements = 0;
1801 
1802   if (!TheCall->getArg(0)->isTypeDependent() &&
1803       !TheCall->getArg(1)->isTypeDependent()) {
1804     QualType LHSType = TheCall->getArg(0)->getType();
1805     QualType RHSType = TheCall->getArg(1)->getType();
1806 
1807     if (!LHSType->isVectorType() || !RHSType->isVectorType())
1808       return ExprError(Diag(TheCall->getLocStart(),
1809                             diag::err_shufflevector_non_vector)
1810                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1811                                       TheCall->getArg(1)->getLocEnd()));
1812 
1813     numElements = LHSType->getAs<VectorType>()->getNumElements();
1814     unsigned numResElements = TheCall->getNumArgs() - 2;
1815 
1816     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1817     // with mask.  If so, verify that RHS is an integer vector type with the
1818     // same number of elts as lhs.
1819     if (TheCall->getNumArgs() == 2) {
1820       if (!RHSType->hasIntegerRepresentation() ||
1821           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1822         return ExprError(Diag(TheCall->getLocStart(),
1823                               diag::err_shufflevector_incompatible_vector)
1824                          << SourceRange(TheCall->getArg(1)->getLocStart(),
1825                                         TheCall->getArg(1)->getLocEnd()));
1826     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1827       return ExprError(Diag(TheCall->getLocStart(),
1828                             diag::err_shufflevector_incompatible_vector)
1829                        << SourceRange(TheCall->getArg(0)->getLocStart(),
1830                                       TheCall->getArg(1)->getLocEnd()));
1831     } else if (numElements != numResElements) {
1832       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1833       resType = Context.getVectorType(eltType, numResElements,
1834                                       VectorType::GenericVector);
1835     }
1836   }
1837 
1838   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1839     if (TheCall->getArg(i)->isTypeDependent() ||
1840         TheCall->getArg(i)->isValueDependent())
1841       continue;
1842 
1843     llvm::APSInt Result(32);
1844     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1845       return ExprError(Diag(TheCall->getLocStart(),
1846                             diag::err_shufflevector_nonconstant_argument)
1847                        << TheCall->getArg(i)->getSourceRange());
1848 
1849     // Allow -1 which will be translated to undef in the IR.
1850     if (Result.isSigned() && Result.isAllOnesValue())
1851       continue;
1852 
1853     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1854       return ExprError(Diag(TheCall->getLocStart(),
1855                             diag::err_shufflevector_argument_too_large)
1856                        << TheCall->getArg(i)->getSourceRange());
1857   }
1858 
1859   SmallVector<Expr*, 32> exprs;
1860 
1861   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1862     exprs.push_back(TheCall->getArg(i));
1863     TheCall->setArg(i, 0);
1864   }
1865 
1866   return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1867                                             TheCall->getCallee()->getLocStart(),
1868                                             TheCall->getRParenLoc()));
1869 }
1870 
1871 /// SemaConvertVectorExpr - Handle __builtin_convertvector
1872 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1873                                        SourceLocation BuiltinLoc,
1874                                        SourceLocation RParenLoc) {
1875   ExprValueKind VK = VK_RValue;
1876   ExprObjectKind OK = OK_Ordinary;
1877   QualType DstTy = TInfo->getType();
1878   QualType SrcTy = E->getType();
1879 
1880   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1881     return ExprError(Diag(BuiltinLoc,
1882                           diag::err_convertvector_non_vector)
1883                      << E->getSourceRange());
1884   if (!DstTy->isVectorType() && !DstTy->isDependentType())
1885     return ExprError(Diag(BuiltinLoc,
1886                           diag::err_convertvector_non_vector_type));
1887 
1888   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1889     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1890     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1891     if (SrcElts != DstElts)
1892       return ExprError(Diag(BuiltinLoc,
1893                             diag::err_convertvector_incompatible_vector)
1894                        << E->getSourceRange());
1895   }
1896 
1897   return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1898                BuiltinLoc, RParenLoc));
1899 
1900 }
1901 
1902 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1903 // This is declared to take (const void*, ...) and can take two
1904 // optional constant int args.
1905 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1906   unsigned NumArgs = TheCall->getNumArgs();
1907 
1908   if (NumArgs > 3)
1909     return Diag(TheCall->getLocEnd(),
1910              diag::err_typecheck_call_too_many_args_at_most)
1911              << 0 /*function call*/ << 3 << NumArgs
1912              << TheCall->getSourceRange();
1913 
1914   // Argument 0 is checked for us and the remaining arguments must be
1915   // constant integers.
1916   for (unsigned i = 1; i != NumArgs; ++i) {
1917     Expr *Arg = TheCall->getArg(i);
1918 
1919     // We can't check the value of a dependent argument.
1920     if (Arg->isTypeDependent() || Arg->isValueDependent())
1921       continue;
1922 
1923     llvm::APSInt Result;
1924     if (SemaBuiltinConstantArg(TheCall, i, Result))
1925       return true;
1926 
1927     // FIXME: gcc issues a warning and rewrites these to 0. These
1928     // seems especially odd for the third argument since the default
1929     // is 3.
1930     if (i == 1) {
1931       if (Result.getLimitedValue() > 1)
1932         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1933              << "0" << "1" << Arg->getSourceRange();
1934     } else {
1935       if (Result.getLimitedValue() > 3)
1936         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1937             << "0" << "3" << Arg->getSourceRange();
1938     }
1939   }
1940 
1941   return false;
1942 }
1943 
1944 /// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1945 // This is declared to take (const char*, int)
1946 bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1947   Expr *Arg = TheCall->getArg(1);
1948 
1949   // We can't check the value of a dependent argument.
1950   if (Arg->isTypeDependent() || Arg->isValueDependent())
1951     return false;
1952 
1953   llvm::APSInt Result;
1954   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1955     return true;
1956 
1957   if (Result.getLimitedValue() > 3)
1958     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1959         << "0" << "3" << Arg->getSourceRange();
1960 
1961   return false;
1962 }
1963 
1964 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1965 /// TheCall is a constant expression.
1966 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1967                                   llvm::APSInt &Result) {
1968   Expr *Arg = TheCall->getArg(ArgNum);
1969   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1970   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1971 
1972   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1973 
1974   if (!Arg->isIntegerConstantExpr(Result, Context))
1975     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1976                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1977 
1978   return false;
1979 }
1980 
1981 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1982 /// int type). This simply type checks that type is one of the defined
1983 /// constants (0-3).
1984 // For compatibility check 0-3, llvm only handles 0 and 2.
1985 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1986   llvm::APSInt Result;
1987 
1988   // We can't check the value of a dependent argument.
1989   if (TheCall->getArg(1)->isTypeDependent() ||
1990       TheCall->getArg(1)->isValueDependent())
1991     return false;
1992 
1993   // Check constant-ness first.
1994   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1995     return true;
1996 
1997   Expr *Arg = TheCall->getArg(1);
1998   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1999     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2000              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2001   }
2002 
2003   return false;
2004 }
2005 
2006 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2007 /// This checks that val is a constant 1.
2008 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2009   Expr *Arg = TheCall->getArg(1);
2010   llvm::APSInt Result;
2011 
2012   // TODO: This is less than ideal. Overload this to take a value.
2013   if (SemaBuiltinConstantArg(TheCall, 1, Result))
2014     return true;
2015 
2016   if (Result != 1)
2017     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2018              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2019 
2020   return false;
2021 }
2022 
2023 namespace {
2024 enum StringLiteralCheckType {
2025   SLCT_NotALiteral,
2026   SLCT_UncheckedLiteral,
2027   SLCT_CheckedLiteral
2028 };
2029 }
2030 
2031 // Determine if an expression is a string literal or constant string.
2032 // If this function returns false on the arguments to a function expecting a
2033 // format string, we will usually need to emit a warning.
2034 // True string literals are then checked by CheckFormatString.
2035 static StringLiteralCheckType
2036 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2037                       bool HasVAListArg, unsigned format_idx,
2038                       unsigned firstDataArg, Sema::FormatStringType Type,
2039                       Sema::VariadicCallType CallType, bool InFunctionCall,
2040                       llvm::SmallBitVector &CheckedVarArgs) {
2041  tryAgain:
2042   if (E->isTypeDependent() || E->isValueDependent())
2043     return SLCT_NotALiteral;
2044 
2045   E = E->IgnoreParenCasts();
2046 
2047   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2048     // Technically -Wformat-nonliteral does not warn about this case.
2049     // The behavior of printf and friends in this case is implementation
2050     // dependent.  Ideally if the format string cannot be null then
2051     // it should have a 'nonnull' attribute in the function prototype.
2052     return SLCT_UncheckedLiteral;
2053 
2054   switch (E->getStmtClass()) {
2055   case Stmt::BinaryConditionalOperatorClass:
2056   case Stmt::ConditionalOperatorClass: {
2057     // The expression is a literal if both sub-expressions were, and it was
2058     // completely checked only if both sub-expressions were checked.
2059     const AbstractConditionalOperator *C =
2060         cast<AbstractConditionalOperator>(E);
2061     StringLiteralCheckType Left =
2062         checkFormatStringExpr(S, C->getTrueExpr(), Args,
2063                               HasVAListArg, format_idx, firstDataArg,
2064                               Type, CallType, InFunctionCall, CheckedVarArgs);
2065     if (Left == SLCT_NotALiteral)
2066       return SLCT_NotALiteral;
2067     StringLiteralCheckType Right =
2068         checkFormatStringExpr(S, C->getFalseExpr(), Args,
2069                               HasVAListArg, format_idx, firstDataArg,
2070                               Type, CallType, InFunctionCall, CheckedVarArgs);
2071     return Left < Right ? Left : Right;
2072   }
2073 
2074   case Stmt::ImplicitCastExprClass: {
2075     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2076     goto tryAgain;
2077   }
2078 
2079   case Stmt::OpaqueValueExprClass:
2080     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2081       E = src;
2082       goto tryAgain;
2083     }
2084     return SLCT_NotALiteral;
2085 
2086   case Stmt::PredefinedExprClass:
2087     // While __func__, etc., are technically not string literals, they
2088     // cannot contain format specifiers and thus are not a security
2089     // liability.
2090     return SLCT_UncheckedLiteral;
2091 
2092   case Stmt::DeclRefExprClass: {
2093     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2094 
2095     // As an exception, do not flag errors for variables binding to
2096     // const string literals.
2097     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2098       bool isConstant = false;
2099       QualType T = DR->getType();
2100 
2101       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2102         isConstant = AT->getElementType().isConstant(S.Context);
2103       } else if (const PointerType *PT = T->getAs<PointerType>()) {
2104         isConstant = T.isConstant(S.Context) &&
2105                      PT->getPointeeType().isConstant(S.Context);
2106       } else if (T->isObjCObjectPointerType()) {
2107         // In ObjC, there is usually no "const ObjectPointer" type,
2108         // so don't check if the pointee type is constant.
2109         isConstant = T.isConstant(S.Context);
2110       }
2111 
2112       if (isConstant) {
2113         if (const Expr *Init = VD->getAnyInitializer()) {
2114           // Look through initializers like const char c[] = { "foo" }
2115           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2116             if (InitList->isStringLiteralInit())
2117               Init = InitList->getInit(0)->IgnoreParenImpCasts();
2118           }
2119           return checkFormatStringExpr(S, Init, Args,
2120                                        HasVAListArg, format_idx,
2121                                        firstDataArg, Type, CallType,
2122                                        /*InFunctionCall*/false, CheckedVarArgs);
2123         }
2124       }
2125 
2126       // For vprintf* functions (i.e., HasVAListArg==true), we add a
2127       // special check to see if the format string is a function parameter
2128       // of the function calling the printf function.  If the function
2129       // has an attribute indicating it is a printf-like function, then we
2130       // should suppress warnings concerning non-literals being used in a call
2131       // to a vprintf function.  For example:
2132       //
2133       // void
2134       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2135       //      va_list ap;
2136       //      va_start(ap, fmt);
2137       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2138       //      ...
2139       // }
2140       if (HasVAListArg) {
2141         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2142           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2143             int PVIndex = PV->getFunctionScopeIndex() + 1;
2144             for (specific_attr_iterator<FormatAttr>
2145                  i = ND->specific_attr_begin<FormatAttr>(),
2146                  e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2147               FormatAttr *PVFormat = *i;
2148               // adjust for implicit parameter
2149               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2150                 if (MD->isInstance())
2151                   ++PVIndex;
2152               // We also check if the formats are compatible.
2153               // We can't pass a 'scanf' string to a 'printf' function.
2154               if (PVIndex == PVFormat->getFormatIdx() &&
2155                   Type == S.GetFormatStringType(PVFormat))
2156                 return SLCT_UncheckedLiteral;
2157             }
2158           }
2159         }
2160       }
2161     }
2162 
2163     return SLCT_NotALiteral;
2164   }
2165 
2166   case Stmt::CallExprClass:
2167   case Stmt::CXXMemberCallExprClass: {
2168     const CallExpr *CE = cast<CallExpr>(E);
2169     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2170       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2171         unsigned ArgIndex = FA->getFormatIdx();
2172         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2173           if (MD->isInstance())
2174             --ArgIndex;
2175         const Expr *Arg = CE->getArg(ArgIndex - 1);
2176 
2177         return checkFormatStringExpr(S, Arg, Args,
2178                                      HasVAListArg, format_idx, firstDataArg,
2179                                      Type, CallType, InFunctionCall,
2180                                      CheckedVarArgs);
2181       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2182         unsigned BuiltinID = FD->getBuiltinID();
2183         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2184             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2185           const Expr *Arg = CE->getArg(0);
2186           return checkFormatStringExpr(S, Arg, Args,
2187                                        HasVAListArg, format_idx,
2188                                        firstDataArg, Type, CallType,
2189                                        InFunctionCall, CheckedVarArgs);
2190         }
2191       }
2192     }
2193 
2194     return SLCT_NotALiteral;
2195   }
2196   case Stmt::ObjCStringLiteralClass:
2197   case Stmt::StringLiteralClass: {
2198     const StringLiteral *StrE = NULL;
2199 
2200     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2201       StrE = ObjCFExpr->getString();
2202     else
2203       StrE = cast<StringLiteral>(E);
2204 
2205     if (StrE) {
2206       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2207                           Type, InFunctionCall, CallType, CheckedVarArgs);
2208       return SLCT_CheckedLiteral;
2209     }
2210 
2211     return SLCT_NotALiteral;
2212   }
2213 
2214   default:
2215     return SLCT_NotALiteral;
2216   }
2217 }
2218 
2219 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2220   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2221   .Case("scanf", FST_Scanf)
2222   .Cases("printf", "printf0", FST_Printf)
2223   .Cases("NSString", "CFString", FST_NSString)
2224   .Case("strftime", FST_Strftime)
2225   .Case("strfmon", FST_Strfmon)
2226   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2227   .Default(FST_Unknown);
2228 }
2229 
2230 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2231 /// functions) for correct use of format strings.
2232 /// Returns true if a format string has been fully checked.
2233 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2234                                 ArrayRef<const Expr *> Args,
2235                                 bool IsCXXMember,
2236                                 VariadicCallType CallType,
2237                                 SourceLocation Loc, SourceRange Range,
2238                                 llvm::SmallBitVector &CheckedVarArgs) {
2239   FormatStringInfo FSI;
2240   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2241     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2242                                 FSI.FirstDataArg, GetFormatStringType(Format),
2243                                 CallType, Loc, Range, CheckedVarArgs);
2244   return false;
2245 }
2246 
2247 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2248                                 bool HasVAListArg, unsigned format_idx,
2249                                 unsigned firstDataArg, FormatStringType Type,
2250                                 VariadicCallType CallType,
2251                                 SourceLocation Loc, SourceRange Range,
2252                                 llvm::SmallBitVector &CheckedVarArgs) {
2253   // CHECK: printf/scanf-like function is called with no format string.
2254   if (format_idx >= Args.size()) {
2255     Diag(Loc, diag::warn_missing_format_string) << Range;
2256     return false;
2257   }
2258 
2259   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2260 
2261   // CHECK: format string is not a string literal.
2262   //
2263   // Dynamically generated format strings are difficult to
2264   // automatically vet at compile time.  Requiring that format strings
2265   // are string literals: (1) permits the checking of format strings by
2266   // the compiler and thereby (2) can practically remove the source of
2267   // many format string exploits.
2268 
2269   // Format string can be either ObjC string (e.g. @"%d") or
2270   // C string (e.g. "%d")
2271   // ObjC string uses the same format specifiers as C string, so we can use
2272   // the same format string checking logic for both ObjC and C strings.
2273   StringLiteralCheckType CT =
2274       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2275                             format_idx, firstDataArg, Type, CallType,
2276                             /*IsFunctionCall*/true, CheckedVarArgs);
2277   if (CT != SLCT_NotALiteral)
2278     // Literal format string found, check done!
2279     return CT == SLCT_CheckedLiteral;
2280 
2281   // Strftime is particular as it always uses a single 'time' argument,
2282   // so it is safe to pass a non-literal string.
2283   if (Type == FST_Strftime)
2284     return false;
2285 
2286   // Do not emit diag when the string param is a macro expansion and the
2287   // format is either NSString or CFString. This is a hack to prevent
2288   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2289   // which are usually used in place of NS and CF string literals.
2290   if (Type == FST_NSString &&
2291       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2292     return false;
2293 
2294   // If there are no arguments specified, warn with -Wformat-security, otherwise
2295   // warn only with -Wformat-nonliteral.
2296   if (Args.size() == firstDataArg)
2297     Diag(Args[format_idx]->getLocStart(),
2298          diag::warn_format_nonliteral_noargs)
2299       << OrigFormatExpr->getSourceRange();
2300   else
2301     Diag(Args[format_idx]->getLocStart(),
2302          diag::warn_format_nonliteral)
2303            << OrigFormatExpr->getSourceRange();
2304   return false;
2305 }
2306 
2307 namespace {
2308 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2309 protected:
2310   Sema &S;
2311   const StringLiteral *FExpr;
2312   const Expr *OrigFormatExpr;
2313   const unsigned FirstDataArg;
2314   const unsigned NumDataArgs;
2315   const char *Beg; // Start of format string.
2316   const bool HasVAListArg;
2317   ArrayRef<const Expr *> Args;
2318   unsigned FormatIdx;
2319   llvm::SmallBitVector CoveredArgs;
2320   bool usesPositionalArgs;
2321   bool atFirstArg;
2322   bool inFunctionCall;
2323   Sema::VariadicCallType CallType;
2324   llvm::SmallBitVector &CheckedVarArgs;
2325 public:
2326   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2327                      const Expr *origFormatExpr, unsigned firstDataArg,
2328                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
2329                      ArrayRef<const Expr *> Args,
2330                      unsigned formatIdx, bool inFunctionCall,
2331                      Sema::VariadicCallType callType,
2332                      llvm::SmallBitVector &CheckedVarArgs)
2333     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2334       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2335       Beg(beg), HasVAListArg(hasVAListArg),
2336       Args(Args), FormatIdx(formatIdx),
2337       usesPositionalArgs(false), atFirstArg(true),
2338       inFunctionCall(inFunctionCall), CallType(callType),
2339       CheckedVarArgs(CheckedVarArgs) {
2340     CoveredArgs.resize(numDataArgs);
2341     CoveredArgs.reset();
2342   }
2343 
2344   void DoneProcessing();
2345 
2346   void HandleIncompleteSpecifier(const char *startSpecifier,
2347                                  unsigned specifierLen);
2348 
2349   void HandleInvalidLengthModifier(
2350       const analyze_format_string::FormatSpecifier &FS,
2351       const analyze_format_string::ConversionSpecifier &CS,
2352       const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2353 
2354   void HandleNonStandardLengthModifier(
2355       const analyze_format_string::FormatSpecifier &FS,
2356       const char *startSpecifier, unsigned specifierLen);
2357 
2358   void HandleNonStandardConversionSpecifier(
2359       const analyze_format_string::ConversionSpecifier &CS,
2360       const char *startSpecifier, unsigned specifierLen);
2361 
2362   virtual void HandlePosition(const char *startPos, unsigned posLen);
2363 
2364   virtual void HandleInvalidPosition(const char *startSpecifier,
2365                                      unsigned specifierLen,
2366                                      analyze_format_string::PositionContext p);
2367 
2368   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2369 
2370   void HandleNullChar(const char *nullCharacter);
2371 
2372   template <typename Range>
2373   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2374                                    const Expr *ArgumentExpr,
2375                                    PartialDiagnostic PDiag,
2376                                    SourceLocation StringLoc,
2377                                    bool IsStringLocation, Range StringRange,
2378                                    ArrayRef<FixItHint> Fixit = None);
2379 
2380 protected:
2381   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2382                                         const char *startSpec,
2383                                         unsigned specifierLen,
2384                                         const char *csStart, unsigned csLen);
2385 
2386   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2387                                          const char *startSpec,
2388                                          unsigned specifierLen);
2389 
2390   SourceRange getFormatStringRange();
2391   CharSourceRange getSpecifierRange(const char *startSpecifier,
2392                                     unsigned specifierLen);
2393   SourceLocation getLocationOfByte(const char *x);
2394 
2395   const Expr *getDataArg(unsigned i) const;
2396 
2397   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2398                     const analyze_format_string::ConversionSpecifier &CS,
2399                     const char *startSpecifier, unsigned specifierLen,
2400                     unsigned argIndex);
2401 
2402   template <typename Range>
2403   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2404                             bool IsStringLocation, Range StringRange,
2405                             ArrayRef<FixItHint> Fixit = None);
2406 
2407   void CheckPositionalAndNonpositionalArgs(
2408       const analyze_format_string::FormatSpecifier *FS);
2409 };
2410 }
2411 
2412 SourceRange CheckFormatHandler::getFormatStringRange() {
2413   return OrigFormatExpr->getSourceRange();
2414 }
2415 
2416 CharSourceRange CheckFormatHandler::
2417 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2418   SourceLocation Start = getLocationOfByte(startSpecifier);
2419   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2420 
2421   // Advance the end SourceLocation by one due to half-open ranges.
2422   End = End.getLocWithOffset(1);
2423 
2424   return CharSourceRange::getCharRange(Start, End);
2425 }
2426 
2427 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2428   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2429 }
2430 
2431 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2432                                                    unsigned specifierLen){
2433   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2434                        getLocationOfByte(startSpecifier),
2435                        /*IsStringLocation*/true,
2436                        getSpecifierRange(startSpecifier, specifierLen));
2437 }
2438 
2439 void CheckFormatHandler::HandleInvalidLengthModifier(
2440     const analyze_format_string::FormatSpecifier &FS,
2441     const analyze_format_string::ConversionSpecifier &CS,
2442     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2443   using namespace analyze_format_string;
2444 
2445   const LengthModifier &LM = FS.getLengthModifier();
2446   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2447 
2448   // See if we know how to fix this length modifier.
2449   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2450   if (FixedLM) {
2451     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2452                          getLocationOfByte(LM.getStart()),
2453                          /*IsStringLocation*/true,
2454                          getSpecifierRange(startSpecifier, specifierLen));
2455 
2456     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2457       << FixedLM->toString()
2458       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2459 
2460   } else {
2461     FixItHint Hint;
2462     if (DiagID == diag::warn_format_nonsensical_length)
2463       Hint = FixItHint::CreateRemoval(LMRange);
2464 
2465     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2466                          getLocationOfByte(LM.getStart()),
2467                          /*IsStringLocation*/true,
2468                          getSpecifierRange(startSpecifier, specifierLen),
2469                          Hint);
2470   }
2471 }
2472 
2473 void CheckFormatHandler::HandleNonStandardLengthModifier(
2474     const analyze_format_string::FormatSpecifier &FS,
2475     const char *startSpecifier, unsigned specifierLen) {
2476   using namespace analyze_format_string;
2477 
2478   const LengthModifier &LM = FS.getLengthModifier();
2479   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2480 
2481   // See if we know how to fix this length modifier.
2482   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2483   if (FixedLM) {
2484     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2485                            << LM.toString() << 0,
2486                          getLocationOfByte(LM.getStart()),
2487                          /*IsStringLocation*/true,
2488                          getSpecifierRange(startSpecifier, specifierLen));
2489 
2490     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2491       << FixedLM->toString()
2492       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2493 
2494   } else {
2495     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2496                            << LM.toString() << 0,
2497                          getLocationOfByte(LM.getStart()),
2498                          /*IsStringLocation*/true,
2499                          getSpecifierRange(startSpecifier, specifierLen));
2500   }
2501 }
2502 
2503 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2504     const analyze_format_string::ConversionSpecifier &CS,
2505     const char *startSpecifier, unsigned specifierLen) {
2506   using namespace analyze_format_string;
2507 
2508   // See if we know how to fix this conversion specifier.
2509   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2510   if (FixedCS) {
2511     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2512                           << CS.toString() << /*conversion specifier*/1,
2513                          getLocationOfByte(CS.getStart()),
2514                          /*IsStringLocation*/true,
2515                          getSpecifierRange(startSpecifier, specifierLen));
2516 
2517     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2518     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2519       << FixedCS->toString()
2520       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2521   } else {
2522     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2523                           << CS.toString() << /*conversion specifier*/1,
2524                          getLocationOfByte(CS.getStart()),
2525                          /*IsStringLocation*/true,
2526                          getSpecifierRange(startSpecifier, specifierLen));
2527   }
2528 }
2529 
2530 void CheckFormatHandler::HandlePosition(const char *startPos,
2531                                         unsigned posLen) {
2532   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2533                                getLocationOfByte(startPos),
2534                                /*IsStringLocation*/true,
2535                                getSpecifierRange(startPos, posLen));
2536 }
2537 
2538 void
2539 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2540                                      analyze_format_string::PositionContext p) {
2541   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2542                          << (unsigned) p,
2543                        getLocationOfByte(startPos), /*IsStringLocation*/true,
2544                        getSpecifierRange(startPos, posLen));
2545 }
2546 
2547 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2548                                             unsigned posLen) {
2549   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2550                                getLocationOfByte(startPos),
2551                                /*IsStringLocation*/true,
2552                                getSpecifierRange(startPos, posLen));
2553 }
2554 
2555 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2556   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2557     // The presence of a null character is likely an error.
2558     EmitFormatDiagnostic(
2559       S.PDiag(diag::warn_printf_format_string_contains_null_char),
2560       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2561       getFormatStringRange());
2562   }
2563 }
2564 
2565 // Note that this may return NULL if there was an error parsing or building
2566 // one of the argument expressions.
2567 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2568   return Args[FirstDataArg + i];
2569 }
2570 
2571 void CheckFormatHandler::DoneProcessing() {
2572     // Does the number of data arguments exceed the number of
2573     // format conversions in the format string?
2574   if (!HasVAListArg) {
2575       // Find any arguments that weren't covered.
2576     CoveredArgs.flip();
2577     signed notCoveredArg = CoveredArgs.find_first();
2578     if (notCoveredArg >= 0) {
2579       assert((unsigned)notCoveredArg < NumDataArgs);
2580       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2581         SourceLocation Loc = E->getLocStart();
2582         if (!S.getSourceManager().isInSystemMacro(Loc)) {
2583           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2584                                Loc, /*IsStringLocation*/false,
2585                                getFormatStringRange());
2586         }
2587       }
2588     }
2589   }
2590 }
2591 
2592 bool
2593 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2594                                                      SourceLocation Loc,
2595                                                      const char *startSpec,
2596                                                      unsigned specifierLen,
2597                                                      const char *csStart,
2598                                                      unsigned csLen) {
2599 
2600   bool keepGoing = true;
2601   if (argIndex < NumDataArgs) {
2602     // Consider the argument coverered, even though the specifier doesn't
2603     // make sense.
2604     CoveredArgs.set(argIndex);
2605   }
2606   else {
2607     // If argIndex exceeds the number of data arguments we
2608     // don't issue a warning because that is just a cascade of warnings (and
2609     // they may have intended '%%' anyway). We don't want to continue processing
2610     // the format string after this point, however, as we will like just get
2611     // gibberish when trying to match arguments.
2612     keepGoing = false;
2613   }
2614 
2615   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2616                          << StringRef(csStart, csLen),
2617                        Loc, /*IsStringLocation*/true,
2618                        getSpecifierRange(startSpec, specifierLen));
2619 
2620   return keepGoing;
2621 }
2622 
2623 void
2624 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2625                                                       const char *startSpec,
2626                                                       unsigned specifierLen) {
2627   EmitFormatDiagnostic(
2628     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2629     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2630 }
2631 
2632 bool
2633 CheckFormatHandler::CheckNumArgs(
2634   const analyze_format_string::FormatSpecifier &FS,
2635   const analyze_format_string::ConversionSpecifier &CS,
2636   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2637 
2638   if (argIndex >= NumDataArgs) {
2639     PartialDiagnostic PDiag = FS.usesPositionalArg()
2640       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2641            << (argIndex+1) << NumDataArgs)
2642       : S.PDiag(diag::warn_printf_insufficient_data_args);
2643     EmitFormatDiagnostic(
2644       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2645       getSpecifierRange(startSpecifier, specifierLen));
2646     return false;
2647   }
2648   return true;
2649 }
2650 
2651 template<typename Range>
2652 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2653                                               SourceLocation Loc,
2654                                               bool IsStringLocation,
2655                                               Range StringRange,
2656                                               ArrayRef<FixItHint> FixIt) {
2657   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2658                        Loc, IsStringLocation, StringRange, FixIt);
2659 }
2660 
2661 /// \brief If the format string is not within the funcion call, emit a note
2662 /// so that the function call and string are in diagnostic messages.
2663 ///
2664 /// \param InFunctionCall if true, the format string is within the function
2665 /// call and only one diagnostic message will be produced.  Otherwise, an
2666 /// extra note will be emitted pointing to location of the format string.
2667 ///
2668 /// \param ArgumentExpr the expression that is passed as the format string
2669 /// argument in the function call.  Used for getting locations when two
2670 /// diagnostics are emitted.
2671 ///
2672 /// \param PDiag the callee should already have provided any strings for the
2673 /// diagnostic message.  This function only adds locations and fixits
2674 /// to diagnostics.
2675 ///
2676 /// \param Loc primary location for diagnostic.  If two diagnostics are
2677 /// required, one will be at Loc and a new SourceLocation will be created for
2678 /// the other one.
2679 ///
2680 /// \param IsStringLocation if true, Loc points to the format string should be
2681 /// used for the note.  Otherwise, Loc points to the argument list and will
2682 /// be used with PDiag.
2683 ///
2684 /// \param StringRange some or all of the string to highlight.  This is
2685 /// templated so it can accept either a CharSourceRange or a SourceRange.
2686 ///
2687 /// \param FixIt optional fix it hint for the format string.
2688 template<typename Range>
2689 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2690                                               const Expr *ArgumentExpr,
2691                                               PartialDiagnostic PDiag,
2692                                               SourceLocation Loc,
2693                                               bool IsStringLocation,
2694                                               Range StringRange,
2695                                               ArrayRef<FixItHint> FixIt) {
2696   if (InFunctionCall) {
2697     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2698     D << StringRange;
2699     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2700          I != E; ++I) {
2701       D << *I;
2702     }
2703   } else {
2704     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2705       << ArgumentExpr->getSourceRange();
2706 
2707     const Sema::SemaDiagnosticBuilder &Note =
2708       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2709              diag::note_format_string_defined);
2710 
2711     Note << StringRange;
2712     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2713          I != E; ++I) {
2714       Note << *I;
2715     }
2716   }
2717 }
2718 
2719 //===--- CHECK: Printf format string checking ------------------------------===//
2720 
2721 namespace {
2722 class CheckPrintfHandler : public CheckFormatHandler {
2723   bool ObjCContext;
2724 public:
2725   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2726                      const Expr *origFormatExpr, unsigned firstDataArg,
2727                      unsigned numDataArgs, bool isObjC,
2728                      const char *beg, bool hasVAListArg,
2729                      ArrayRef<const Expr *> Args,
2730                      unsigned formatIdx, bool inFunctionCall,
2731                      Sema::VariadicCallType CallType,
2732                      llvm::SmallBitVector &CheckedVarArgs)
2733     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2734                          numDataArgs, beg, hasVAListArg, Args,
2735                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2736       ObjCContext(isObjC)
2737   {}
2738 
2739 
2740   bool HandleInvalidPrintfConversionSpecifier(
2741                                       const analyze_printf::PrintfSpecifier &FS,
2742                                       const char *startSpecifier,
2743                                       unsigned specifierLen);
2744 
2745   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2746                              const char *startSpecifier,
2747                              unsigned specifierLen);
2748   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2749                        const char *StartSpecifier,
2750                        unsigned SpecifierLen,
2751                        const Expr *E);
2752 
2753   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2754                     const char *startSpecifier, unsigned specifierLen);
2755   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2756                            const analyze_printf::OptionalAmount &Amt,
2757                            unsigned type,
2758                            const char *startSpecifier, unsigned specifierLen);
2759   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2760                   const analyze_printf::OptionalFlag &flag,
2761                   const char *startSpecifier, unsigned specifierLen);
2762   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2763                          const analyze_printf::OptionalFlag &ignoredFlag,
2764                          const analyze_printf::OptionalFlag &flag,
2765                          const char *startSpecifier, unsigned specifierLen);
2766   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2767                            const Expr *E);
2768 
2769 };
2770 }
2771 
2772 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2773                                       const analyze_printf::PrintfSpecifier &FS,
2774                                       const char *startSpecifier,
2775                                       unsigned specifierLen) {
2776   const analyze_printf::PrintfConversionSpecifier &CS =
2777     FS.getConversionSpecifier();
2778 
2779   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2780                                           getLocationOfByte(CS.getStart()),
2781                                           startSpecifier, specifierLen,
2782                                           CS.getStart(), CS.getLength());
2783 }
2784 
2785 bool CheckPrintfHandler::HandleAmount(
2786                                const analyze_format_string::OptionalAmount &Amt,
2787                                unsigned k, const char *startSpecifier,
2788                                unsigned specifierLen) {
2789 
2790   if (Amt.hasDataArgument()) {
2791     if (!HasVAListArg) {
2792       unsigned argIndex = Amt.getArgIndex();
2793       if (argIndex >= NumDataArgs) {
2794         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2795                                << k,
2796                              getLocationOfByte(Amt.getStart()),
2797                              /*IsStringLocation*/true,
2798                              getSpecifierRange(startSpecifier, specifierLen));
2799         // Don't do any more checking.  We will just emit
2800         // spurious errors.
2801         return false;
2802       }
2803 
2804       // Type check the data argument.  It should be an 'int'.
2805       // Although not in conformance with C99, we also allow the argument to be
2806       // an 'unsigned int' as that is a reasonably safe case.  GCC also
2807       // doesn't emit a warning for that case.
2808       CoveredArgs.set(argIndex);
2809       const Expr *Arg = getDataArg(argIndex);
2810       if (!Arg)
2811         return false;
2812 
2813       QualType T = Arg->getType();
2814 
2815       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2816       assert(AT.isValid());
2817 
2818       if (!AT.matchesType(S.Context, T)) {
2819         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2820                                << k << AT.getRepresentativeTypeName(S.Context)
2821                                << T << Arg->getSourceRange(),
2822                              getLocationOfByte(Amt.getStart()),
2823                              /*IsStringLocation*/true,
2824                              getSpecifierRange(startSpecifier, specifierLen));
2825         // Don't do any more checking.  We will just emit
2826         // spurious errors.
2827         return false;
2828       }
2829     }
2830   }
2831   return true;
2832 }
2833 
2834 void CheckPrintfHandler::HandleInvalidAmount(
2835                                       const analyze_printf::PrintfSpecifier &FS,
2836                                       const analyze_printf::OptionalAmount &Amt,
2837                                       unsigned type,
2838                                       const char *startSpecifier,
2839                                       unsigned specifierLen) {
2840   const analyze_printf::PrintfConversionSpecifier &CS =
2841     FS.getConversionSpecifier();
2842 
2843   FixItHint fixit =
2844     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2845       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2846                                  Amt.getConstantLength()))
2847       : FixItHint();
2848 
2849   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2850                          << type << CS.toString(),
2851                        getLocationOfByte(Amt.getStart()),
2852                        /*IsStringLocation*/true,
2853                        getSpecifierRange(startSpecifier, specifierLen),
2854                        fixit);
2855 }
2856 
2857 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2858                                     const analyze_printf::OptionalFlag &flag,
2859                                     const char *startSpecifier,
2860                                     unsigned specifierLen) {
2861   // Warn about pointless flag with a fixit removal.
2862   const analyze_printf::PrintfConversionSpecifier &CS =
2863     FS.getConversionSpecifier();
2864   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2865                          << flag.toString() << CS.toString(),
2866                        getLocationOfByte(flag.getPosition()),
2867                        /*IsStringLocation*/true,
2868                        getSpecifierRange(startSpecifier, specifierLen),
2869                        FixItHint::CreateRemoval(
2870                          getSpecifierRange(flag.getPosition(), 1)));
2871 }
2872 
2873 void CheckPrintfHandler::HandleIgnoredFlag(
2874                                 const analyze_printf::PrintfSpecifier &FS,
2875                                 const analyze_printf::OptionalFlag &ignoredFlag,
2876                                 const analyze_printf::OptionalFlag &flag,
2877                                 const char *startSpecifier,
2878                                 unsigned specifierLen) {
2879   // Warn about ignored flag with a fixit removal.
2880   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2881                          << ignoredFlag.toString() << flag.toString(),
2882                        getLocationOfByte(ignoredFlag.getPosition()),
2883                        /*IsStringLocation*/true,
2884                        getSpecifierRange(startSpecifier, specifierLen),
2885                        FixItHint::CreateRemoval(
2886                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
2887 }
2888 
2889 // Determines if the specified is a C++ class or struct containing
2890 // a member with the specified name and kind (e.g. a CXXMethodDecl named
2891 // "c_str()").
2892 template<typename MemberKind>
2893 static llvm::SmallPtrSet<MemberKind*, 1>
2894 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2895   const RecordType *RT = Ty->getAs<RecordType>();
2896   llvm::SmallPtrSet<MemberKind*, 1> Results;
2897 
2898   if (!RT)
2899     return Results;
2900   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2901   if (!RD || !RD->getDefinition())
2902     return Results;
2903 
2904   LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2905                  Sema::LookupMemberName);
2906   R.suppressDiagnostics();
2907 
2908   // We just need to include all members of the right kind turned up by the
2909   // filter, at this point.
2910   if (S.LookupQualifiedName(R, RT->getDecl()))
2911     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2912       NamedDecl *decl = (*I)->getUnderlyingDecl();
2913       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2914         Results.insert(FK);
2915     }
2916   return Results;
2917 }
2918 
2919 /// Check if we could call '.c_str()' on an object.
2920 ///
2921 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2922 /// allow the call, or if it would be ambiguous).
2923 bool Sema::hasCStrMethod(const Expr *E) {
2924   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2925   MethodSet Results =
2926       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2927   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2928        MI != ME; ++MI)
2929     if ((*MI)->getMinRequiredArguments() == 0)
2930       return true;
2931   return false;
2932 }
2933 
2934 // Check if a (w)string was passed when a (w)char* was needed, and offer a
2935 // better diagnostic if so. AT is assumed to be valid.
2936 // Returns true when a c_str() conversion method is found.
2937 bool CheckPrintfHandler::checkForCStrMembers(
2938     const analyze_printf::ArgType &AT, const Expr *E) {
2939   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2940 
2941   MethodSet Results =
2942       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2943 
2944   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2945        MI != ME; ++MI) {
2946     const CXXMethodDecl *Method = *MI;
2947     if (Method->getMinRequiredArguments() == 0 &&
2948         AT.matchesType(S.Context, Method->getReturnType())) {
2949       // FIXME: Suggest parens if the expression needs them.
2950       SourceLocation EndLoc =
2951           S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2952       S.Diag(E->getLocStart(), diag::note_printf_c_str)
2953           << "c_str()"
2954           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2955       return true;
2956     }
2957   }
2958 
2959   return false;
2960 }
2961 
2962 bool
2963 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2964                                             &FS,
2965                                           const char *startSpecifier,
2966                                           unsigned specifierLen) {
2967 
2968   using namespace analyze_format_string;
2969   using namespace analyze_printf;
2970   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2971 
2972   if (FS.consumesDataArgument()) {
2973     if (atFirstArg) {
2974         atFirstArg = false;
2975         usesPositionalArgs = FS.usesPositionalArg();
2976     }
2977     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2978       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2979                                         startSpecifier, specifierLen);
2980       return false;
2981     }
2982   }
2983 
2984   // First check if the field width, precision, and conversion specifier
2985   // have matching data arguments.
2986   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2987                     startSpecifier, specifierLen)) {
2988     return false;
2989   }
2990 
2991   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2992                     startSpecifier, specifierLen)) {
2993     return false;
2994   }
2995 
2996   if (!CS.consumesDataArgument()) {
2997     // FIXME: Technically specifying a precision or field width here
2998     // makes no sense.  Worth issuing a warning at some point.
2999     return true;
3000   }
3001 
3002   // Consume the argument.
3003   unsigned argIndex = FS.getArgIndex();
3004   if (argIndex < NumDataArgs) {
3005     // The check to see if the argIndex is valid will come later.
3006     // We set the bit here because we may exit early from this
3007     // function if we encounter some other error.
3008     CoveredArgs.set(argIndex);
3009   }
3010 
3011   // Check for using an Objective-C specific conversion specifier
3012   // in a non-ObjC literal.
3013   if (!ObjCContext && CS.isObjCArg()) {
3014     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3015                                                   specifierLen);
3016   }
3017 
3018   // Check for invalid use of field width
3019   if (!FS.hasValidFieldWidth()) {
3020     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3021         startSpecifier, specifierLen);
3022   }
3023 
3024   // Check for invalid use of precision
3025   if (!FS.hasValidPrecision()) {
3026     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3027         startSpecifier, specifierLen);
3028   }
3029 
3030   // Check each flag does not conflict with any other component.
3031   if (!FS.hasValidThousandsGroupingPrefix())
3032     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3033   if (!FS.hasValidLeadingZeros())
3034     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3035   if (!FS.hasValidPlusPrefix())
3036     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3037   if (!FS.hasValidSpacePrefix())
3038     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3039   if (!FS.hasValidAlternativeForm())
3040     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3041   if (!FS.hasValidLeftJustified())
3042     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3043 
3044   // Check that flags are not ignored by another flag
3045   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3046     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3047         startSpecifier, specifierLen);
3048   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3049     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3050             startSpecifier, specifierLen);
3051 
3052   // Check the length modifier is valid with the given conversion specifier.
3053   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3054     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3055                                 diag::warn_format_nonsensical_length);
3056   else if (!FS.hasStandardLengthModifier())
3057     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3058   else if (!FS.hasStandardLengthConversionCombination())
3059     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3060                                 diag::warn_format_non_standard_conversion_spec);
3061 
3062   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3063     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3064 
3065   // The remaining checks depend on the data arguments.
3066   if (HasVAListArg)
3067     return true;
3068 
3069   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3070     return false;
3071 
3072   const Expr *Arg = getDataArg(argIndex);
3073   if (!Arg)
3074     return true;
3075 
3076   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3077 }
3078 
3079 static bool requiresParensToAddCast(const Expr *E) {
3080   // FIXME: We should have a general way to reason about operator
3081   // precedence and whether parens are actually needed here.
3082   // Take care of a few common cases where they aren't.
3083   const Expr *Inside = E->IgnoreImpCasts();
3084   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3085     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3086 
3087   switch (Inside->getStmtClass()) {
3088   case Stmt::ArraySubscriptExprClass:
3089   case Stmt::CallExprClass:
3090   case Stmt::CharacterLiteralClass:
3091   case Stmt::CXXBoolLiteralExprClass:
3092   case Stmt::DeclRefExprClass:
3093   case Stmt::FloatingLiteralClass:
3094   case Stmt::IntegerLiteralClass:
3095   case Stmt::MemberExprClass:
3096   case Stmt::ObjCArrayLiteralClass:
3097   case Stmt::ObjCBoolLiteralExprClass:
3098   case Stmt::ObjCBoxedExprClass:
3099   case Stmt::ObjCDictionaryLiteralClass:
3100   case Stmt::ObjCEncodeExprClass:
3101   case Stmt::ObjCIvarRefExprClass:
3102   case Stmt::ObjCMessageExprClass:
3103   case Stmt::ObjCPropertyRefExprClass:
3104   case Stmt::ObjCStringLiteralClass:
3105   case Stmt::ObjCSubscriptRefExprClass:
3106   case Stmt::ParenExprClass:
3107   case Stmt::StringLiteralClass:
3108   case Stmt::UnaryOperatorClass:
3109     return false;
3110   default:
3111     return true;
3112   }
3113 }
3114 
3115 bool
3116 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3117                                     const char *StartSpecifier,
3118                                     unsigned SpecifierLen,
3119                                     const Expr *E) {
3120   using namespace analyze_format_string;
3121   using namespace analyze_printf;
3122   // Now type check the data expression that matches the
3123   // format specifier.
3124   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3125                                                     ObjCContext);
3126   if (!AT.isValid())
3127     return true;
3128 
3129   QualType ExprTy = E->getType();
3130   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3131     ExprTy = TET->getUnderlyingExpr()->getType();
3132   }
3133 
3134   if (AT.matchesType(S.Context, ExprTy))
3135     return true;
3136 
3137   // Look through argument promotions for our error message's reported type.
3138   // This includes the integral and floating promotions, but excludes array
3139   // and function pointer decay; seeing that an argument intended to be a
3140   // string has type 'char [6]' is probably more confusing than 'char *'.
3141   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3142     if (ICE->getCastKind() == CK_IntegralCast ||
3143         ICE->getCastKind() == CK_FloatingCast) {
3144       E = ICE->getSubExpr();
3145       ExprTy = E->getType();
3146 
3147       // Check if we didn't match because of an implicit cast from a 'char'
3148       // or 'short' to an 'int'.  This is done because printf is a varargs
3149       // function.
3150       if (ICE->getType() == S.Context.IntTy ||
3151           ICE->getType() == S.Context.UnsignedIntTy) {
3152         // All further checking is done on the subexpression.
3153         if (AT.matchesType(S.Context, ExprTy))
3154           return true;
3155       }
3156     }
3157   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3158     // Special case for 'a', which has type 'int' in C.
3159     // Note, however, that we do /not/ want to treat multibyte constants like
3160     // 'MooV' as characters! This form is deprecated but still exists.
3161     if (ExprTy == S.Context.IntTy)
3162       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3163         ExprTy = S.Context.CharTy;
3164   }
3165 
3166   // %C in an Objective-C context prints a unichar, not a wchar_t.
3167   // If the argument is an integer of some kind, believe the %C and suggest
3168   // a cast instead of changing the conversion specifier.
3169   QualType IntendedTy = ExprTy;
3170   if (ObjCContext &&
3171       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3172     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3173         !ExprTy->isCharType()) {
3174       // 'unichar' is defined as a typedef of unsigned short, but we should
3175       // prefer using the typedef if it is visible.
3176       IntendedTy = S.Context.UnsignedShortTy;
3177 
3178       // While we are here, check if the value is an IntegerLiteral that happens
3179       // to be within the valid range.
3180       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3181         const llvm::APInt &V = IL->getValue();
3182         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3183           return true;
3184       }
3185 
3186       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3187                           Sema::LookupOrdinaryName);
3188       if (S.LookupName(Result, S.getCurScope())) {
3189         NamedDecl *ND = Result.getFoundDecl();
3190         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3191           if (TD->getUnderlyingType() == IntendedTy)
3192             IntendedTy = S.Context.getTypedefType(TD);
3193       }
3194     }
3195   }
3196 
3197   // Special-case some of Darwin's platform-independence types by suggesting
3198   // casts to primitive types that are known to be large enough.
3199   bool ShouldNotPrintDirectly = false;
3200   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3201     // Use a 'while' to peel off layers of typedefs.
3202     QualType TyTy = IntendedTy;
3203     while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3204       StringRef Name = UserTy->getDecl()->getName();
3205       QualType CastTy = llvm::StringSwitch<QualType>(Name)
3206         .Case("NSInteger", S.Context.LongTy)
3207         .Case("NSUInteger", S.Context.UnsignedLongTy)
3208         .Case("SInt32", S.Context.IntTy)
3209         .Case("UInt32", S.Context.UnsignedIntTy)
3210         .Default(QualType());
3211 
3212       if (!CastTy.isNull()) {
3213         ShouldNotPrintDirectly = true;
3214         IntendedTy = CastTy;
3215         break;
3216       }
3217       TyTy = UserTy->desugar();
3218     }
3219   }
3220 
3221   // We may be able to offer a FixItHint if it is a supported type.
3222   PrintfSpecifier fixedFS = FS;
3223   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3224                                  S.Context, ObjCContext);
3225 
3226   if (success) {
3227     // Get the fix string from the fixed format specifier
3228     SmallString<16> buf;
3229     llvm::raw_svector_ostream os(buf);
3230     fixedFS.toString(os);
3231 
3232     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3233 
3234     if (IntendedTy == ExprTy) {
3235       // In this case, the specifier is wrong and should be changed to match
3236       // the argument.
3237       EmitFormatDiagnostic(
3238         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3239           << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3240           << E->getSourceRange(),
3241         E->getLocStart(),
3242         /*IsStringLocation*/false,
3243         SpecRange,
3244         FixItHint::CreateReplacement(SpecRange, os.str()));
3245 
3246     } else {
3247       // The canonical type for formatting this value is different from the
3248       // actual type of the expression. (This occurs, for example, with Darwin's
3249       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3250       // should be printed as 'long' for 64-bit compatibility.)
3251       // Rather than emitting a normal format/argument mismatch, we want to
3252       // add a cast to the recommended type (and correct the format string
3253       // if necessary).
3254       SmallString<16> CastBuf;
3255       llvm::raw_svector_ostream CastFix(CastBuf);
3256       CastFix << "(";
3257       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3258       CastFix << ")";
3259 
3260       SmallVector<FixItHint,4> Hints;
3261       if (!AT.matchesType(S.Context, IntendedTy))
3262         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3263 
3264       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3265         // If there's already a cast present, just replace it.
3266         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3267         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3268 
3269       } else if (!requiresParensToAddCast(E)) {
3270         // If the expression has high enough precedence,
3271         // just write the C-style cast.
3272         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3273                                                    CastFix.str()));
3274       } else {
3275         // Otherwise, add parens around the expression as well as the cast.
3276         CastFix << "(";
3277         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3278                                                    CastFix.str()));
3279 
3280         SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3281         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3282       }
3283 
3284       if (ShouldNotPrintDirectly) {
3285         // The expression has a type that should not be printed directly.
3286         // We extract the name from the typedef because we don't want to show
3287         // the underlying type in the diagnostic.
3288         StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3289 
3290         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3291                                << Name << IntendedTy
3292                                << E->getSourceRange(),
3293                              E->getLocStart(), /*IsStringLocation=*/false,
3294                              SpecRange, Hints);
3295       } else {
3296         // In this case, the expression could be printed using a different
3297         // specifier, but we've decided that the specifier is probably correct
3298         // and we should cast instead. Just use the normal warning message.
3299         EmitFormatDiagnostic(
3300           S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3301             << AT.getRepresentativeTypeName(S.Context) << ExprTy
3302             << E->getSourceRange(),
3303           E->getLocStart(), /*IsStringLocation*/false,
3304           SpecRange, Hints);
3305       }
3306     }
3307   } else {
3308     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3309                                                    SpecifierLen);
3310     // Since the warning for passing non-POD types to variadic functions
3311     // was deferred until now, we emit a warning for non-POD
3312     // arguments here.
3313     switch (S.isValidVarArgType(ExprTy)) {
3314     case Sema::VAK_Valid:
3315     case Sema::VAK_ValidInCXX11:
3316       EmitFormatDiagnostic(
3317         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3318           << AT.getRepresentativeTypeName(S.Context) << ExprTy
3319           << CSR
3320           << E->getSourceRange(),
3321         E->getLocStart(), /*IsStringLocation*/false, CSR);
3322       break;
3323 
3324     case Sema::VAK_Undefined:
3325       EmitFormatDiagnostic(
3326         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3327           << S.getLangOpts().CPlusPlus11
3328           << ExprTy
3329           << CallType
3330           << AT.getRepresentativeTypeName(S.Context)
3331           << CSR
3332           << E->getSourceRange(),
3333         E->getLocStart(), /*IsStringLocation*/false, CSR);
3334       checkForCStrMembers(AT, E);
3335       break;
3336 
3337     case Sema::VAK_Invalid:
3338       if (ExprTy->isObjCObjectType())
3339         EmitFormatDiagnostic(
3340           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3341             << S.getLangOpts().CPlusPlus11
3342             << ExprTy
3343             << CallType
3344             << AT.getRepresentativeTypeName(S.Context)
3345             << CSR
3346             << E->getSourceRange(),
3347           E->getLocStart(), /*IsStringLocation*/false, CSR);
3348       else
3349         // FIXME: If this is an initializer list, suggest removing the braces
3350         // or inserting a cast to the target type.
3351         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3352           << isa<InitListExpr>(E) << ExprTy << CallType
3353           << AT.getRepresentativeTypeName(S.Context)
3354           << E->getSourceRange();
3355       break;
3356     }
3357 
3358     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3359            "format string specifier index out of range");
3360     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3361   }
3362 
3363   return true;
3364 }
3365 
3366 //===--- CHECK: Scanf format string checking ------------------------------===//
3367 
3368 namespace {
3369 class CheckScanfHandler : public CheckFormatHandler {
3370 public:
3371   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3372                     const Expr *origFormatExpr, unsigned firstDataArg,
3373                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
3374                     ArrayRef<const Expr *> Args,
3375                     unsigned formatIdx, bool inFunctionCall,
3376                     Sema::VariadicCallType CallType,
3377                     llvm::SmallBitVector &CheckedVarArgs)
3378     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3379                          numDataArgs, beg, hasVAListArg,
3380                          Args, formatIdx, inFunctionCall, CallType,
3381                          CheckedVarArgs)
3382   {}
3383 
3384   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3385                             const char *startSpecifier,
3386                             unsigned specifierLen);
3387 
3388   bool HandleInvalidScanfConversionSpecifier(
3389           const analyze_scanf::ScanfSpecifier &FS,
3390           const char *startSpecifier,
3391           unsigned specifierLen);
3392 
3393   void HandleIncompleteScanList(const char *start, const char *end);
3394 };
3395 }
3396 
3397 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3398                                                  const char *end) {
3399   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3400                        getLocationOfByte(end), /*IsStringLocation*/true,
3401                        getSpecifierRange(start, end - start));
3402 }
3403 
3404 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3405                                         const analyze_scanf::ScanfSpecifier &FS,
3406                                         const char *startSpecifier,
3407                                         unsigned specifierLen) {
3408 
3409   const analyze_scanf::ScanfConversionSpecifier &CS =
3410     FS.getConversionSpecifier();
3411 
3412   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3413                                           getLocationOfByte(CS.getStart()),
3414                                           startSpecifier, specifierLen,
3415                                           CS.getStart(), CS.getLength());
3416 }
3417 
3418 bool CheckScanfHandler::HandleScanfSpecifier(
3419                                        const analyze_scanf::ScanfSpecifier &FS,
3420                                        const char *startSpecifier,
3421                                        unsigned specifierLen) {
3422 
3423   using namespace analyze_scanf;
3424   using namespace analyze_format_string;
3425 
3426   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3427 
3428   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3429   // be used to decide if we are using positional arguments consistently.
3430   if (FS.consumesDataArgument()) {
3431     if (atFirstArg) {
3432       atFirstArg = false;
3433       usesPositionalArgs = FS.usesPositionalArg();
3434     }
3435     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3436       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3437                                         startSpecifier, specifierLen);
3438       return false;
3439     }
3440   }
3441 
3442   // Check if the field with is non-zero.
3443   const OptionalAmount &Amt = FS.getFieldWidth();
3444   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3445     if (Amt.getConstantAmount() == 0) {
3446       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3447                                                    Amt.getConstantLength());
3448       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3449                            getLocationOfByte(Amt.getStart()),
3450                            /*IsStringLocation*/true, R,
3451                            FixItHint::CreateRemoval(R));
3452     }
3453   }
3454 
3455   if (!FS.consumesDataArgument()) {
3456     // FIXME: Technically specifying a precision or field width here
3457     // makes no sense.  Worth issuing a warning at some point.
3458     return true;
3459   }
3460 
3461   // Consume the argument.
3462   unsigned argIndex = FS.getArgIndex();
3463   if (argIndex < NumDataArgs) {
3464       // The check to see if the argIndex is valid will come later.
3465       // We set the bit here because we may exit early from this
3466       // function if we encounter some other error.
3467     CoveredArgs.set(argIndex);
3468   }
3469 
3470   // Check the length modifier is valid with the given conversion specifier.
3471   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3472     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3473                                 diag::warn_format_nonsensical_length);
3474   else if (!FS.hasStandardLengthModifier())
3475     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3476   else if (!FS.hasStandardLengthConversionCombination())
3477     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3478                                 diag::warn_format_non_standard_conversion_spec);
3479 
3480   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3481     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3482 
3483   // The remaining checks depend on the data arguments.
3484   if (HasVAListArg)
3485     return true;
3486 
3487   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3488     return false;
3489 
3490   // Check that the argument type matches the format specifier.
3491   const Expr *Ex = getDataArg(argIndex);
3492   if (!Ex)
3493     return true;
3494 
3495   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3496   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3497     ScanfSpecifier fixedFS = FS;
3498     bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3499                                    S.Context);
3500 
3501     if (success) {
3502       // Get the fix string from the fixed format specifier.
3503       SmallString<128> buf;
3504       llvm::raw_svector_ostream os(buf);
3505       fixedFS.toString(os);
3506 
3507       EmitFormatDiagnostic(
3508         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3509           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3510           << Ex->getSourceRange(),
3511         Ex->getLocStart(),
3512         /*IsStringLocation*/false,
3513         getSpecifierRange(startSpecifier, specifierLen),
3514         FixItHint::CreateReplacement(
3515           getSpecifierRange(startSpecifier, specifierLen),
3516           os.str()));
3517     } else {
3518       EmitFormatDiagnostic(
3519         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3520           << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3521           << Ex->getSourceRange(),
3522         Ex->getLocStart(),
3523         /*IsStringLocation*/false,
3524         getSpecifierRange(startSpecifier, specifierLen));
3525     }
3526   }
3527 
3528   return true;
3529 }
3530 
3531 void Sema::CheckFormatString(const StringLiteral *FExpr,
3532                              const Expr *OrigFormatExpr,
3533                              ArrayRef<const Expr *> Args,
3534                              bool HasVAListArg, unsigned format_idx,
3535                              unsigned firstDataArg, FormatStringType Type,
3536                              bool inFunctionCall, VariadicCallType CallType,
3537                              llvm::SmallBitVector &CheckedVarArgs) {
3538 
3539   // CHECK: is the format string a wide literal?
3540   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3541     CheckFormatHandler::EmitFormatDiagnostic(
3542       *this, inFunctionCall, Args[format_idx],
3543       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3544       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3545     return;
3546   }
3547 
3548   // Str - The format string.  NOTE: this is NOT null-terminated!
3549   StringRef StrRef = FExpr->getString();
3550   const char *Str = StrRef.data();
3551   // Account for cases where the string literal is truncated in a declaration.
3552   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3553   assert(T && "String literal not of constant array type!");
3554   size_t TypeSize = T->getSize().getZExtValue();
3555   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3556   const unsigned numDataArgs = Args.size() - firstDataArg;
3557 
3558   // Emit a warning if the string literal is truncated and does not contain an
3559   // embedded null character.
3560   if (TypeSize <= StrRef.size() &&
3561       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3562     CheckFormatHandler::EmitFormatDiagnostic(
3563         *this, inFunctionCall, Args[format_idx],
3564         PDiag(diag::warn_printf_format_string_not_null_terminated),
3565         FExpr->getLocStart(),
3566         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3567     return;
3568   }
3569 
3570   // CHECK: empty format string?
3571   if (StrLen == 0 && numDataArgs > 0) {
3572     CheckFormatHandler::EmitFormatDiagnostic(
3573       *this, inFunctionCall, Args[format_idx],
3574       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3575       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3576     return;
3577   }
3578 
3579   if (Type == FST_Printf || Type == FST_NSString) {
3580     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3581                          numDataArgs, (Type == FST_NSString),
3582                          Str, HasVAListArg, Args, format_idx,
3583                          inFunctionCall, CallType, CheckedVarArgs);
3584 
3585     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3586                                                   getLangOpts(),
3587                                                   Context.getTargetInfo()))
3588       H.DoneProcessing();
3589   } else if (Type == FST_Scanf) {
3590     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3591                         Str, HasVAListArg, Args, format_idx,
3592                         inFunctionCall, CallType, CheckedVarArgs);
3593 
3594     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3595                                                  getLangOpts(),
3596                                                  Context.getTargetInfo()))
3597       H.DoneProcessing();
3598   } // TODO: handle other formats
3599 }
3600 
3601 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3602 
3603 // Returns the related absolute value function that is larger, of 0 if one
3604 // does not exist.
3605 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3606   switch (AbsFunction) {
3607   default:
3608     return 0;
3609 
3610   case Builtin::BI__builtin_abs:
3611     return Builtin::BI__builtin_labs;
3612   case Builtin::BI__builtin_labs:
3613     return Builtin::BI__builtin_llabs;
3614   case Builtin::BI__builtin_llabs:
3615     return 0;
3616 
3617   case Builtin::BI__builtin_fabsf:
3618     return Builtin::BI__builtin_fabs;
3619   case Builtin::BI__builtin_fabs:
3620     return Builtin::BI__builtin_fabsl;
3621   case Builtin::BI__builtin_fabsl:
3622     return 0;
3623 
3624   case Builtin::BI__builtin_cabsf:
3625     return Builtin::BI__builtin_cabs;
3626   case Builtin::BI__builtin_cabs:
3627     return Builtin::BI__builtin_cabsl;
3628   case Builtin::BI__builtin_cabsl:
3629     return 0;
3630 
3631   case Builtin::BIabs:
3632     return Builtin::BIlabs;
3633   case Builtin::BIlabs:
3634     return Builtin::BIllabs;
3635   case Builtin::BIllabs:
3636     return 0;
3637 
3638   case Builtin::BIfabsf:
3639     return Builtin::BIfabs;
3640   case Builtin::BIfabs:
3641     return Builtin::BIfabsl;
3642   case Builtin::BIfabsl:
3643     return 0;
3644 
3645   case Builtin::BIcabsf:
3646    return Builtin::BIcabs;
3647   case Builtin::BIcabs:
3648     return Builtin::BIcabsl;
3649   case Builtin::BIcabsl:
3650     return 0;
3651   }
3652 }
3653 
3654 // Returns the argument type of the absolute value function.
3655 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3656                                              unsigned AbsType) {
3657   if (AbsType == 0)
3658     return QualType();
3659 
3660   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3661   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3662   if (Error != ASTContext::GE_None)
3663     return QualType();
3664 
3665   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3666   if (!FT)
3667     return QualType();
3668 
3669   if (FT->getNumParams() != 1)
3670     return QualType();
3671 
3672   return FT->getParamType(0);
3673 }
3674 
3675 // Returns the best absolute value function, or zero, based on type and
3676 // current absolute value function.
3677 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3678                                    unsigned AbsFunctionKind) {
3679   unsigned BestKind = 0;
3680   uint64_t ArgSize = Context.getTypeSize(ArgType);
3681   for (unsigned Kind = AbsFunctionKind; Kind != 0;
3682        Kind = getLargerAbsoluteValueFunction(Kind)) {
3683     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3684     if (Context.getTypeSize(ParamType) >= ArgSize) {
3685       if (BestKind == 0)
3686         BestKind = Kind;
3687       else if (Context.hasSameType(ParamType, ArgType)) {
3688         BestKind = Kind;
3689         break;
3690       }
3691     }
3692   }
3693   return BestKind;
3694 }
3695 
3696 enum AbsoluteValueKind {
3697   AVK_Integer,
3698   AVK_Floating,
3699   AVK_Complex
3700 };
3701 
3702 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3703   if (T->isIntegralOrEnumerationType())
3704     return AVK_Integer;
3705   if (T->isRealFloatingType())
3706     return AVK_Floating;
3707   if (T->isAnyComplexType())
3708     return AVK_Complex;
3709 
3710   llvm_unreachable("Type not integer, floating, or complex");
3711 }
3712 
3713 // Changes the absolute value function to a different type.  Preserves whether
3714 // the function is a builtin.
3715 static unsigned changeAbsFunction(unsigned AbsKind,
3716                                   AbsoluteValueKind ValueKind) {
3717   switch (ValueKind) {
3718   case AVK_Integer:
3719     switch (AbsKind) {
3720     default:
3721       return 0;
3722     case Builtin::BI__builtin_fabsf:
3723     case Builtin::BI__builtin_fabs:
3724     case Builtin::BI__builtin_fabsl:
3725     case Builtin::BI__builtin_cabsf:
3726     case Builtin::BI__builtin_cabs:
3727     case Builtin::BI__builtin_cabsl:
3728       return Builtin::BI__builtin_abs;
3729     case Builtin::BIfabsf:
3730     case Builtin::BIfabs:
3731     case Builtin::BIfabsl:
3732     case Builtin::BIcabsf:
3733     case Builtin::BIcabs:
3734     case Builtin::BIcabsl:
3735       return Builtin::BIabs;
3736     }
3737   case AVK_Floating:
3738     switch (AbsKind) {
3739     default:
3740       return 0;
3741     case Builtin::BI__builtin_abs:
3742     case Builtin::BI__builtin_labs:
3743     case Builtin::BI__builtin_llabs:
3744     case Builtin::BI__builtin_cabsf:
3745     case Builtin::BI__builtin_cabs:
3746     case Builtin::BI__builtin_cabsl:
3747       return Builtin::BI__builtin_fabsf;
3748     case Builtin::BIabs:
3749     case Builtin::BIlabs:
3750     case Builtin::BIllabs:
3751     case Builtin::BIcabsf:
3752     case Builtin::BIcabs:
3753     case Builtin::BIcabsl:
3754       return Builtin::BIfabsf;
3755     }
3756   case AVK_Complex:
3757     switch (AbsKind) {
3758     default:
3759       return 0;
3760     case Builtin::BI__builtin_abs:
3761     case Builtin::BI__builtin_labs:
3762     case Builtin::BI__builtin_llabs:
3763     case Builtin::BI__builtin_fabsf:
3764     case Builtin::BI__builtin_fabs:
3765     case Builtin::BI__builtin_fabsl:
3766       return Builtin::BI__builtin_cabsf;
3767     case Builtin::BIabs:
3768     case Builtin::BIlabs:
3769     case Builtin::BIllabs:
3770     case Builtin::BIfabsf:
3771     case Builtin::BIfabs:
3772     case Builtin::BIfabsl:
3773       return Builtin::BIcabsf;
3774     }
3775   }
3776   llvm_unreachable("Unable to convert function");
3777 }
3778 
3779 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
3780   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3781   if (!FnInfo)
3782     return 0;
3783 
3784   switch (FDecl->getBuiltinID()) {
3785   default:
3786     return 0;
3787   case Builtin::BI__builtin_abs:
3788   case Builtin::BI__builtin_fabs:
3789   case Builtin::BI__builtin_fabsf:
3790   case Builtin::BI__builtin_fabsl:
3791   case Builtin::BI__builtin_labs:
3792   case Builtin::BI__builtin_llabs:
3793   case Builtin::BI__builtin_cabs:
3794   case Builtin::BI__builtin_cabsf:
3795   case Builtin::BI__builtin_cabsl:
3796   case Builtin::BIabs:
3797   case Builtin::BIlabs:
3798   case Builtin::BIllabs:
3799   case Builtin::BIfabs:
3800   case Builtin::BIfabsf:
3801   case Builtin::BIfabsl:
3802   case Builtin::BIcabs:
3803   case Builtin::BIcabsf:
3804   case Builtin::BIcabsl:
3805     return FDecl->getBuiltinID();
3806   }
3807   llvm_unreachable("Unknown Builtin type");
3808 }
3809 
3810 // If the replacement is valid, emit a note with replacement function.
3811 // Additionally, suggest including the proper header if not already included.
3812 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3813                             unsigned AbsKind) {
3814   std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3815 
3816   // Look up absolute value function in TU scope.
3817   DeclarationName DN(&S.Context.Idents.get(AbsName));
3818   LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3819   R.suppressDiagnostics();
3820   S.LookupName(R, S.TUScope);
3821 
3822   // Skip notes if multiple results found in lookup.
3823   if (!R.empty() && !R.isSingleResult())
3824     return;
3825 
3826   FunctionDecl *FD = 0;
3827   bool FoundFunction = R.isSingleResult();
3828   // When one result is found, see if it is the correct function.
3829   if (R.isSingleResult()) {
3830     FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3831     if (!FD || FD->getBuiltinID() != AbsKind)
3832       return;
3833   }
3834 
3835   // Look for local name conflict, prepend "::" as necessary.
3836   R.clear();
3837   S.LookupName(R, S.getCurScope());
3838 
3839   if (!FoundFunction) {
3840     if (!R.empty()) {
3841       AbsName = "::" + AbsName;
3842     }
3843   } else { // FoundFunction
3844     if (R.isSingleResult()) {
3845       if (R.getFoundDecl() != FD) {
3846         AbsName = "::" + AbsName;
3847       }
3848     } else if (!R.empty()) {
3849       AbsName = "::" + AbsName;
3850     }
3851   }
3852 
3853   S.Diag(Loc, diag::note_replace_abs_function)
3854       << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3855 
3856   if (!FoundFunction) {
3857     S.Diag(Loc, diag::note_please_include_header)
3858         << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3859         << S.Context.BuiltinInfo.GetName(AbsKind);
3860   }
3861 }
3862 
3863 // Warn when using the wrong abs() function.
3864 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3865                                       const FunctionDecl *FDecl,
3866                                       IdentifierInfo *FnInfo) {
3867   if (Call->getNumArgs() != 1)
3868     return;
3869 
3870   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3871   if (AbsKind == 0)
3872     return;
3873 
3874   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3875   QualType ParamType = Call->getArg(0)->getType();
3876 
3877   // Unsigned types can not be negative.  Suggest to drop the absolute value
3878   // function.
3879   if (ArgType->isUnsignedIntegerType()) {
3880     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3881     Diag(Call->getExprLoc(), diag::note_remove_abs)
3882         << FDecl
3883         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3884     return;
3885   }
3886 
3887   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3888   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3889 
3890   // The argument and parameter are the same kind.  Check if they are the right
3891   // size.
3892   if (ArgValueKind == ParamValueKind) {
3893     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3894       return;
3895 
3896     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3897     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3898         << FDecl << ArgType << ParamType;
3899 
3900     if (NewAbsKind == 0)
3901       return;
3902 
3903     emitReplacement(*this, Call->getExprLoc(),
3904                     Call->getCallee()->getSourceRange(), NewAbsKind);
3905     return;
3906   }
3907 
3908   // ArgValueKind != ParamValueKind
3909   // The wrong type of absolute value function was used.  Attempt to find the
3910   // proper one.
3911   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3912   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3913   if (NewAbsKind == 0)
3914     return;
3915 
3916   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3917       << FDecl << ParamValueKind << ArgValueKind;
3918 
3919   emitReplacement(*this, Call->getExprLoc(),
3920                   Call->getCallee()->getSourceRange(), NewAbsKind);
3921   return;
3922 }
3923 
3924 //===--- CHECK: Standard memory functions ---------------------------------===//
3925 
3926 /// \brief Takes the expression passed to the size_t parameter of functions
3927 /// such as memcmp, strncat, etc and warns if it's a comparison.
3928 ///
3929 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3930 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3931                                            IdentifierInfo *FnName,
3932                                            SourceLocation FnLoc,
3933                                            SourceLocation RParenLoc) {
3934   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3935   if (!Size)
3936     return false;
3937 
3938   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3939   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3940     return false;
3941 
3942   Preprocessor &PP = S.getPreprocessor();
3943   SourceRange SizeRange = Size->getSourceRange();
3944   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3945       << SizeRange << FnName;
3946   S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3947       << FnName
3948       << FixItHint::CreateInsertion(
3949              PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3950              ")")
3951       << FixItHint::CreateRemoval(RParenLoc);
3952   S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3953       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3954       << FixItHint::CreateInsertion(
3955              PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3956 
3957   return true;
3958 }
3959 
3960 /// \brief Determine whether the given type is a dynamic class type (e.g.,
3961 /// whether it has a vtable).
3962 static bool isDynamicClassType(QualType T) {
3963   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3964     if (CXXRecordDecl *Definition = Record->getDefinition())
3965       if (Definition->isDynamicClass())
3966         return true;
3967 
3968   return false;
3969 }
3970 
3971 /// \brief If E is a sizeof expression, returns its argument expression,
3972 /// otherwise returns NULL.
3973 static const Expr *getSizeOfExprArg(const Expr* E) {
3974   if (const UnaryExprOrTypeTraitExpr *SizeOf =
3975       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3976     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3977       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3978 
3979   return 0;
3980 }
3981 
3982 /// \brief If E is a sizeof expression, returns its argument type.
3983 static QualType getSizeOfArgType(const Expr* E) {
3984   if (const UnaryExprOrTypeTraitExpr *SizeOf =
3985       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3986     if (SizeOf->getKind() == clang::UETT_SizeOf)
3987       return SizeOf->getTypeOfArgument();
3988 
3989   return QualType();
3990 }
3991 
3992 /// \brief Check for dangerous or invalid arguments to memset().
3993 ///
3994 /// This issues warnings on known problematic, dangerous or unspecified
3995 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3996 /// function calls.
3997 ///
3998 /// \param Call The call expression to diagnose.
3999 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4000                                    unsigned BId,
4001                                    IdentifierInfo *FnName) {
4002   assert(BId != 0);
4003 
4004   // It is possible to have a non-standard definition of memset.  Validate
4005   // we have enough arguments, and if not, abort further checking.
4006   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4007   if (Call->getNumArgs() < ExpectedNumArgs)
4008     return;
4009 
4010   unsigned LastArg = (BId == Builtin::BImemset ||
4011                       BId == Builtin::BIstrndup ? 1 : 2);
4012   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4013   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4014 
4015   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4016                                      Call->getLocStart(), Call->getRParenLoc()))
4017     return;
4018 
4019   // We have special checking when the length is a sizeof expression.
4020   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4021   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4022   llvm::FoldingSetNodeID SizeOfArgID;
4023 
4024   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4025     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4026     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4027 
4028     QualType DestTy = Dest->getType();
4029     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4030       QualType PointeeTy = DestPtrTy->getPointeeType();
4031 
4032       // Never warn about void type pointers. This can be used to suppress
4033       // false positives.
4034       if (PointeeTy->isVoidType())
4035         continue;
4036 
4037       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4038       // actually comparing the expressions for equality. Because computing the
4039       // expression IDs can be expensive, we only do this if the diagnostic is
4040       // enabled.
4041       if (SizeOfArg &&
4042           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4043                                    SizeOfArg->getExprLoc())) {
4044         // We only compute IDs for expressions if the warning is enabled, and
4045         // cache the sizeof arg's ID.
4046         if (SizeOfArgID == llvm::FoldingSetNodeID())
4047           SizeOfArg->Profile(SizeOfArgID, Context, true);
4048         llvm::FoldingSetNodeID DestID;
4049         Dest->Profile(DestID, Context, true);
4050         if (DestID == SizeOfArgID) {
4051           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4052           //       over sizeof(src) as well.
4053           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4054           StringRef ReadableName = FnName->getName();
4055 
4056           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4057             if (UnaryOp->getOpcode() == UO_AddrOf)
4058               ActionIdx = 1; // If its an address-of operator, just remove it.
4059           if (!PointeeTy->isIncompleteType() &&
4060               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4061             ActionIdx = 2; // If the pointee's size is sizeof(char),
4062                            // suggest an explicit length.
4063 
4064           // If the function is defined as a builtin macro, do not show macro
4065           // expansion.
4066           SourceLocation SL = SizeOfArg->getExprLoc();
4067           SourceRange DSR = Dest->getSourceRange();
4068           SourceRange SSR = SizeOfArg->getSourceRange();
4069           SourceManager &SM  = PP.getSourceManager();
4070 
4071           if (SM.isMacroArgExpansion(SL)) {
4072             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4073             SL = SM.getSpellingLoc(SL);
4074             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4075                              SM.getSpellingLoc(DSR.getEnd()));
4076             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4077                              SM.getSpellingLoc(SSR.getEnd()));
4078           }
4079 
4080           DiagRuntimeBehavior(SL, SizeOfArg,
4081                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4082                                 << ReadableName
4083                                 << PointeeTy
4084                                 << DestTy
4085                                 << DSR
4086                                 << SSR);
4087           DiagRuntimeBehavior(SL, SizeOfArg,
4088                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4089                                 << ActionIdx
4090                                 << SSR);
4091 
4092           break;
4093         }
4094       }
4095 
4096       // Also check for cases where the sizeof argument is the exact same
4097       // type as the memory argument, and where it points to a user-defined
4098       // record type.
4099       if (SizeOfArgTy != QualType()) {
4100         if (PointeeTy->isRecordType() &&
4101             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4102           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4103                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
4104                                 << FnName << SizeOfArgTy << ArgIdx
4105                                 << PointeeTy << Dest->getSourceRange()
4106                                 << LenExpr->getSourceRange());
4107           break;
4108         }
4109       }
4110 
4111       // Always complain about dynamic classes.
4112       if (isDynamicClassType(PointeeTy)) {
4113 
4114         unsigned OperationType = 0;
4115         // "overwritten" if we're warning about the destination for any call
4116         // but memcmp; otherwise a verb appropriate to the call.
4117         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4118           if (BId == Builtin::BImemcpy)
4119             OperationType = 1;
4120           else if(BId == Builtin::BImemmove)
4121             OperationType = 2;
4122           else if (BId == Builtin::BImemcmp)
4123             OperationType = 3;
4124         }
4125 
4126         DiagRuntimeBehavior(
4127           Dest->getExprLoc(), Dest,
4128           PDiag(diag::warn_dyn_class_memaccess)
4129             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4130             << FnName << PointeeTy
4131             << OperationType
4132             << Call->getCallee()->getSourceRange());
4133       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4134                BId != Builtin::BImemset)
4135         DiagRuntimeBehavior(
4136           Dest->getExprLoc(), Dest,
4137           PDiag(diag::warn_arc_object_memaccess)
4138             << ArgIdx << FnName << PointeeTy
4139             << Call->getCallee()->getSourceRange());
4140       else
4141         continue;
4142 
4143       DiagRuntimeBehavior(
4144         Dest->getExprLoc(), Dest,
4145         PDiag(diag::note_bad_memaccess_silence)
4146           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4147       break;
4148     }
4149   }
4150 }
4151 
4152 // A little helper routine: ignore addition and subtraction of integer literals.
4153 // This intentionally does not ignore all integer constant expressions because
4154 // we don't want to remove sizeof().
4155 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4156   Ex = Ex->IgnoreParenCasts();
4157 
4158   for (;;) {
4159     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4160     if (!BO || !BO->isAdditiveOp())
4161       break;
4162 
4163     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4164     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4165 
4166     if (isa<IntegerLiteral>(RHS))
4167       Ex = LHS;
4168     else if (isa<IntegerLiteral>(LHS))
4169       Ex = RHS;
4170     else
4171       break;
4172   }
4173 
4174   return Ex;
4175 }
4176 
4177 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4178                                                       ASTContext &Context) {
4179   // Only handle constant-sized or VLAs, but not flexible members.
4180   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4181     // Only issue the FIXIT for arrays of size > 1.
4182     if (CAT->getSize().getSExtValue() <= 1)
4183       return false;
4184   } else if (!Ty->isVariableArrayType()) {
4185     return false;
4186   }
4187   return true;
4188 }
4189 
4190 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4191 // be the size of the source, instead of the destination.
4192 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4193                                     IdentifierInfo *FnName) {
4194 
4195   // Don't crash if the user has the wrong number of arguments
4196   if (Call->getNumArgs() != 3)
4197     return;
4198 
4199   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4200   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4201   const Expr *CompareWithSrc = NULL;
4202 
4203   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4204                                      Call->getLocStart(), Call->getRParenLoc()))
4205     return;
4206 
4207   // Look for 'strlcpy(dst, x, sizeof(x))'
4208   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4209     CompareWithSrc = Ex;
4210   else {
4211     // Look for 'strlcpy(dst, x, strlen(x))'
4212     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4213       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4214           SizeCall->getNumArgs() == 1)
4215         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4216     }
4217   }
4218 
4219   if (!CompareWithSrc)
4220     return;
4221 
4222   // Determine if the argument to sizeof/strlen is equal to the source
4223   // argument.  In principle there's all kinds of things you could do
4224   // here, for instance creating an == expression and evaluating it with
4225   // EvaluateAsBooleanCondition, but this uses a more direct technique:
4226   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4227   if (!SrcArgDRE)
4228     return;
4229 
4230   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4231   if (!CompareWithSrcDRE ||
4232       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4233     return;
4234 
4235   const Expr *OriginalSizeArg = Call->getArg(2);
4236   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4237     << OriginalSizeArg->getSourceRange() << FnName;
4238 
4239   // Output a FIXIT hint if the destination is an array (rather than a
4240   // pointer to an array).  This could be enhanced to handle some
4241   // pointers if we know the actual size, like if DstArg is 'array+2'
4242   // we could say 'sizeof(array)-2'.
4243   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4244   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4245     return;
4246 
4247   SmallString<128> sizeString;
4248   llvm::raw_svector_ostream OS(sizeString);
4249   OS << "sizeof(";
4250   DstArg->printPretty(OS, 0, getPrintingPolicy());
4251   OS << ")";
4252 
4253   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4254     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4255                                     OS.str());
4256 }
4257 
4258 /// Check if two expressions refer to the same declaration.
4259 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4260   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4261     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4262       return D1->getDecl() == D2->getDecl();
4263   return false;
4264 }
4265 
4266 static const Expr *getStrlenExprArg(const Expr *E) {
4267   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4268     const FunctionDecl *FD = CE->getDirectCallee();
4269     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4270       return 0;
4271     return CE->getArg(0)->IgnoreParenCasts();
4272   }
4273   return 0;
4274 }
4275 
4276 // Warn on anti-patterns as the 'size' argument to strncat.
4277 // The correct size argument should look like following:
4278 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4279 void Sema::CheckStrncatArguments(const CallExpr *CE,
4280                                  IdentifierInfo *FnName) {
4281   // Don't crash if the user has the wrong number of arguments.
4282   if (CE->getNumArgs() < 3)
4283     return;
4284   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4285   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4286   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4287 
4288   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4289                                      CE->getRParenLoc()))
4290     return;
4291 
4292   // Identify common expressions, which are wrongly used as the size argument
4293   // to strncat and may lead to buffer overflows.
4294   unsigned PatternType = 0;
4295   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4296     // - sizeof(dst)
4297     if (referToTheSameDecl(SizeOfArg, DstArg))
4298       PatternType = 1;
4299     // - sizeof(src)
4300     else if (referToTheSameDecl(SizeOfArg, SrcArg))
4301       PatternType = 2;
4302   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4303     if (BE->getOpcode() == BO_Sub) {
4304       const Expr *L = BE->getLHS()->IgnoreParenCasts();
4305       const Expr *R = BE->getRHS()->IgnoreParenCasts();
4306       // - sizeof(dst) - strlen(dst)
4307       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4308           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4309         PatternType = 1;
4310       // - sizeof(src) - (anything)
4311       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4312         PatternType = 2;
4313     }
4314   }
4315 
4316   if (PatternType == 0)
4317     return;
4318 
4319   // Generate the diagnostic.
4320   SourceLocation SL = LenArg->getLocStart();
4321   SourceRange SR = LenArg->getSourceRange();
4322   SourceManager &SM  = PP.getSourceManager();
4323 
4324   // If the function is defined as a builtin macro, do not show macro expansion.
4325   if (SM.isMacroArgExpansion(SL)) {
4326     SL = SM.getSpellingLoc(SL);
4327     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4328                      SM.getSpellingLoc(SR.getEnd()));
4329   }
4330 
4331   // Check if the destination is an array (rather than a pointer to an array).
4332   QualType DstTy = DstArg->getType();
4333   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4334                                                                     Context);
4335   if (!isKnownSizeArray) {
4336     if (PatternType == 1)
4337       Diag(SL, diag::warn_strncat_wrong_size) << SR;
4338     else
4339       Diag(SL, diag::warn_strncat_src_size) << SR;
4340     return;
4341   }
4342 
4343   if (PatternType == 1)
4344     Diag(SL, diag::warn_strncat_large_size) << SR;
4345   else
4346     Diag(SL, diag::warn_strncat_src_size) << SR;
4347 
4348   SmallString<128> sizeString;
4349   llvm::raw_svector_ostream OS(sizeString);
4350   OS << "sizeof(";
4351   DstArg->printPretty(OS, 0, getPrintingPolicy());
4352   OS << ") - ";
4353   OS << "strlen(";
4354   DstArg->printPretty(OS, 0, getPrintingPolicy());
4355   OS << ") - 1";
4356 
4357   Diag(SL, diag::note_strncat_wrong_size)
4358     << FixItHint::CreateReplacement(SR, OS.str());
4359 }
4360 
4361 //===--- CHECK: Return Address of Stack Variable --------------------------===//
4362 
4363 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4364                      Decl *ParentDecl);
4365 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4366                       Decl *ParentDecl);
4367 
4368 /// CheckReturnStackAddr - Check if a return statement returns the address
4369 ///   of a stack variable.
4370 static void
4371 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4372                      SourceLocation ReturnLoc) {
4373 
4374   Expr *stackE = 0;
4375   SmallVector<DeclRefExpr *, 8> refVars;
4376 
4377   // Perform checking for returned stack addresses, local blocks,
4378   // label addresses or references to temporaries.
4379   if (lhsType->isPointerType() ||
4380       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4381     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
4382   } else if (lhsType->isReferenceType()) {
4383     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
4384   }
4385 
4386   if (stackE == 0)
4387     return; // Nothing suspicious was found.
4388 
4389   SourceLocation diagLoc;
4390   SourceRange diagRange;
4391   if (refVars.empty()) {
4392     diagLoc = stackE->getLocStart();
4393     diagRange = stackE->getSourceRange();
4394   } else {
4395     // We followed through a reference variable. 'stackE' contains the
4396     // problematic expression but we will warn at the return statement pointing
4397     // at the reference variable. We will later display the "trail" of
4398     // reference variables using notes.
4399     diagLoc = refVars[0]->getLocStart();
4400     diagRange = refVars[0]->getSourceRange();
4401   }
4402 
4403   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4404     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4405                                              : diag::warn_ret_stack_addr)
4406      << DR->getDecl()->getDeclName() << diagRange;
4407   } else if (isa<BlockExpr>(stackE)) { // local block.
4408     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4409   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4410     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4411   } else { // local temporary.
4412     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4413                                                : diag::warn_ret_local_temp_addr)
4414      << diagRange;
4415   }
4416 
4417   // Display the "trail" of reference variables that we followed until we
4418   // found the problematic expression using notes.
4419   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4420     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4421     // If this var binds to another reference var, show the range of the next
4422     // var, otherwise the var binds to the problematic expression, in which case
4423     // show the range of the expression.
4424     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4425                                   : stackE->getSourceRange();
4426     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4427         << VD->getDeclName() << range;
4428   }
4429 }
4430 
4431 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4432 ///  check if the expression in a return statement evaluates to an address
4433 ///  to a location on the stack, a local block, an address of a label, or a
4434 ///  reference to local temporary. The recursion is used to traverse the
4435 ///  AST of the return expression, with recursion backtracking when we
4436 ///  encounter a subexpression that (1) clearly does not lead to one of the
4437 ///  above problematic expressions (2) is something we cannot determine leads to
4438 ///  a problematic expression based on such local checking.
4439 ///
4440 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4441 ///  the expression that they point to. Such variables are added to the
4442 ///  'refVars' vector so that we know what the reference variable "trail" was.
4443 ///
4444 ///  EvalAddr processes expressions that are pointers that are used as
4445 ///  references (and not L-values).  EvalVal handles all other values.
4446 ///  At the base case of the recursion is a check for the above problematic
4447 ///  expressions.
4448 ///
4449 ///  This implementation handles:
4450 ///
4451 ///   * pointer-to-pointer casts
4452 ///   * implicit conversions from array references to pointers
4453 ///   * taking the address of fields
4454 ///   * arbitrary interplay between "&" and "*" operators
4455 ///   * pointer arithmetic from an address of a stack variable
4456 ///   * taking the address of an array element where the array is on the stack
4457 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4458                       Decl *ParentDecl) {
4459   if (E->isTypeDependent())
4460     return NULL;
4461 
4462   // We should only be called for evaluating pointer expressions.
4463   assert((E->getType()->isAnyPointerType() ||
4464           E->getType()->isBlockPointerType() ||
4465           E->getType()->isObjCQualifiedIdType()) &&
4466          "EvalAddr only works on pointers");
4467 
4468   E = E->IgnoreParens();
4469 
4470   // Our "symbolic interpreter" is just a dispatch off the currently
4471   // viewed AST node.  We then recursively traverse the AST by calling
4472   // EvalAddr and EvalVal appropriately.
4473   switch (E->getStmtClass()) {
4474   case Stmt::DeclRefExprClass: {
4475     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4476 
4477     // If we leave the immediate function, the lifetime isn't about to end.
4478     if (DR->refersToEnclosingLocal())
4479       return 0;
4480 
4481     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4482       // If this is a reference variable, follow through to the expression that
4483       // it points to.
4484       if (V->hasLocalStorage() &&
4485           V->getType()->isReferenceType() && V->hasInit()) {
4486         // Add the reference variable to the "trail".
4487         refVars.push_back(DR);
4488         return EvalAddr(V->getInit(), refVars, ParentDecl);
4489       }
4490 
4491     return NULL;
4492   }
4493 
4494   case Stmt::UnaryOperatorClass: {
4495     // The only unary operator that make sense to handle here
4496     // is AddrOf.  All others don't make sense as pointers.
4497     UnaryOperator *U = cast<UnaryOperator>(E);
4498 
4499     if (U->getOpcode() == UO_AddrOf)
4500       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4501     else
4502       return NULL;
4503   }
4504 
4505   case Stmt::BinaryOperatorClass: {
4506     // Handle pointer arithmetic.  All other binary operators are not valid
4507     // in this context.
4508     BinaryOperator *B = cast<BinaryOperator>(E);
4509     BinaryOperatorKind op = B->getOpcode();
4510 
4511     if (op != BO_Add && op != BO_Sub)
4512       return NULL;
4513 
4514     Expr *Base = B->getLHS();
4515 
4516     // Determine which argument is the real pointer base.  It could be
4517     // the RHS argument instead of the LHS.
4518     if (!Base->getType()->isPointerType()) Base = B->getRHS();
4519 
4520     assert (Base->getType()->isPointerType());
4521     return EvalAddr(Base, refVars, ParentDecl);
4522   }
4523 
4524   // For conditional operators we need to see if either the LHS or RHS are
4525   // valid DeclRefExpr*s.  If one of them is valid, we return it.
4526   case Stmt::ConditionalOperatorClass: {
4527     ConditionalOperator *C = cast<ConditionalOperator>(E);
4528 
4529     // Handle the GNU extension for missing LHS.
4530     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4531     if (Expr *LHSExpr = C->getLHS()) {
4532       // In C++, we can have a throw-expression, which has 'void' type.
4533       if (!LHSExpr->getType()->isVoidType())
4534         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
4535           return LHS;
4536     }
4537 
4538     // In C++, we can have a throw-expression, which has 'void' type.
4539     if (C->getRHS()->getType()->isVoidType())
4540       return 0;
4541 
4542     return EvalAddr(C->getRHS(), refVars, ParentDecl);
4543   }
4544 
4545   case Stmt::BlockExprClass:
4546     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4547       return E; // local block.
4548     return NULL;
4549 
4550   case Stmt::AddrLabelExprClass:
4551     return E; // address of label.
4552 
4553   case Stmt::ExprWithCleanupsClass:
4554     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4555                     ParentDecl);
4556 
4557   // For casts, we need to handle conversions from arrays to
4558   // pointer values, and pointer-to-pointer conversions.
4559   case Stmt::ImplicitCastExprClass:
4560   case Stmt::CStyleCastExprClass:
4561   case Stmt::CXXFunctionalCastExprClass:
4562   case Stmt::ObjCBridgedCastExprClass:
4563   case Stmt::CXXStaticCastExprClass:
4564   case Stmt::CXXDynamicCastExprClass:
4565   case Stmt::CXXConstCastExprClass:
4566   case Stmt::CXXReinterpretCastExprClass: {
4567     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4568     switch (cast<CastExpr>(E)->getCastKind()) {
4569     case CK_BitCast:
4570     case CK_LValueToRValue:
4571     case CK_NoOp:
4572     case CK_BaseToDerived:
4573     case CK_DerivedToBase:
4574     case CK_UncheckedDerivedToBase:
4575     case CK_Dynamic:
4576     case CK_CPointerToObjCPointerCast:
4577     case CK_BlockPointerToObjCPointerCast:
4578     case CK_AnyPointerToBlockPointerCast:
4579       return EvalAddr(SubExpr, refVars, ParentDecl);
4580 
4581     case CK_ArrayToPointerDecay:
4582       return EvalVal(SubExpr, refVars, ParentDecl);
4583 
4584     default:
4585       return 0;
4586     }
4587   }
4588 
4589   case Stmt::MaterializeTemporaryExprClass:
4590     if (Expr *Result = EvalAddr(
4591                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4592                                 refVars, ParentDecl))
4593       return Result;
4594 
4595     return E;
4596 
4597   // Everything else: we simply don't reason about them.
4598   default:
4599     return NULL;
4600   }
4601 }
4602 
4603 
4604 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
4605 ///   See the comments for EvalAddr for more details.
4606 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4607                      Decl *ParentDecl) {
4608 do {
4609   // We should only be called for evaluating non-pointer expressions, or
4610   // expressions with a pointer type that are not used as references but instead
4611   // are l-values (e.g., DeclRefExpr with a pointer type).
4612 
4613   // Our "symbolic interpreter" is just a dispatch off the currently
4614   // viewed AST node.  We then recursively traverse the AST by calling
4615   // EvalAddr and EvalVal appropriately.
4616 
4617   E = E->IgnoreParens();
4618   switch (E->getStmtClass()) {
4619   case Stmt::ImplicitCastExprClass: {
4620     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4621     if (IE->getValueKind() == VK_LValue) {
4622       E = IE->getSubExpr();
4623       continue;
4624     }
4625     return NULL;
4626   }
4627 
4628   case Stmt::ExprWithCleanupsClass:
4629     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4630 
4631   case Stmt::DeclRefExprClass: {
4632     // When we hit a DeclRefExpr we are looking at code that refers to a
4633     // variable's name. If it's not a reference variable we check if it has
4634     // local storage within the function, and if so, return the expression.
4635     DeclRefExpr *DR = cast<DeclRefExpr>(E);
4636 
4637     // If we leave the immediate function, the lifetime isn't about to end.
4638     if (DR->refersToEnclosingLocal())
4639       return 0;
4640 
4641     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4642       // Check if it refers to itself, e.g. "int& i = i;".
4643       if (V == ParentDecl)
4644         return DR;
4645 
4646       if (V->hasLocalStorage()) {
4647         if (!V->getType()->isReferenceType())
4648           return DR;
4649 
4650         // Reference variable, follow through to the expression that
4651         // it points to.
4652         if (V->hasInit()) {
4653           // Add the reference variable to the "trail".
4654           refVars.push_back(DR);
4655           return EvalVal(V->getInit(), refVars, V);
4656         }
4657       }
4658     }
4659 
4660     return NULL;
4661   }
4662 
4663   case Stmt::UnaryOperatorClass: {
4664     // The only unary operator that make sense to handle here
4665     // is Deref.  All others don't resolve to a "name."  This includes
4666     // handling all sorts of rvalues passed to a unary operator.
4667     UnaryOperator *U = cast<UnaryOperator>(E);
4668 
4669     if (U->getOpcode() == UO_Deref)
4670       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4671 
4672     return NULL;
4673   }
4674 
4675   case Stmt::ArraySubscriptExprClass: {
4676     // Array subscripts are potential references to data on the stack.  We
4677     // retrieve the DeclRefExpr* for the array variable if it indeed
4678     // has local storage.
4679     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4680   }
4681 
4682   case Stmt::ConditionalOperatorClass: {
4683     // For conditional operators we need to see if either the LHS or RHS are
4684     // non-NULL Expr's.  If one is non-NULL, we return it.
4685     ConditionalOperator *C = cast<ConditionalOperator>(E);
4686 
4687     // Handle the GNU extension for missing LHS.
4688     if (Expr *LHSExpr = C->getLHS()) {
4689       // In C++, we can have a throw-expression, which has 'void' type.
4690       if (!LHSExpr->getType()->isVoidType())
4691         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4692           return LHS;
4693     }
4694 
4695     // In C++, we can have a throw-expression, which has 'void' type.
4696     if (C->getRHS()->getType()->isVoidType())
4697       return 0;
4698 
4699     return EvalVal(C->getRHS(), refVars, ParentDecl);
4700   }
4701 
4702   // Accesses to members are potential references to data on the stack.
4703   case Stmt::MemberExprClass: {
4704     MemberExpr *M = cast<MemberExpr>(E);
4705 
4706     // Check for indirect access.  We only want direct field accesses.
4707     if (M->isArrow())
4708       return NULL;
4709 
4710     // Check whether the member type is itself a reference, in which case
4711     // we're not going to refer to the member, but to what the member refers to.
4712     if (M->getMemberDecl()->getType()->isReferenceType())
4713       return NULL;
4714 
4715     return EvalVal(M->getBase(), refVars, ParentDecl);
4716   }
4717 
4718   case Stmt::MaterializeTemporaryExprClass:
4719     if (Expr *Result = EvalVal(
4720                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4721                                refVars, ParentDecl))
4722       return Result;
4723 
4724     return E;
4725 
4726   default:
4727     // Check that we don't return or take the address of a reference to a
4728     // temporary. This is only useful in C++.
4729     if (!E->isTypeDependent() && E->isRValue())
4730       return E;
4731 
4732     // Everything else: we simply don't reason about them.
4733     return NULL;
4734   }
4735 } while (true);
4736 }
4737 
4738 void
4739 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4740                          SourceLocation ReturnLoc,
4741                          bool isObjCMethod,
4742                          const AttrVec *Attrs,
4743                          const FunctionDecl *FD) {
4744   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4745 
4746   // Check if the return value is null but should not be.
4747   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4748       CheckNonNullExpr(*this, RetValExp))
4749     Diag(ReturnLoc, diag::warn_null_ret)
4750       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4751 
4752   // C++11 [basic.stc.dynamic.allocation]p4:
4753   //   If an allocation function declared with a non-throwing
4754   //   exception-specification fails to allocate storage, it shall return
4755   //   a null pointer. Any other allocation function that fails to allocate
4756   //   storage shall indicate failure only by throwing an exception [...]
4757   if (FD) {
4758     OverloadedOperatorKind Op = FD->getOverloadedOperator();
4759     if (Op == OO_New || Op == OO_Array_New) {
4760       const FunctionProtoType *Proto
4761         = FD->getType()->castAs<FunctionProtoType>();
4762       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4763           CheckNonNullExpr(*this, RetValExp))
4764         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4765           << FD << getLangOpts().CPlusPlus11;
4766     }
4767   }
4768 }
4769 
4770 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4771 
4772 /// Check for comparisons of floating point operands using != and ==.
4773 /// Issue a warning if these are no self-comparisons, as they are not likely
4774 /// to do what the programmer intended.
4775 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4776   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4777   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4778 
4779   // Special case: check for x == x (which is OK).
4780   // Do not emit warnings for such cases.
4781   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4782     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4783       if (DRL->getDecl() == DRR->getDecl())
4784         return;
4785 
4786 
4787   // Special case: check for comparisons against literals that can be exactly
4788   //  represented by APFloat.  In such cases, do not emit a warning.  This
4789   //  is a heuristic: often comparison against such literals are used to
4790   //  detect if a value in a variable has not changed.  This clearly can
4791   //  lead to false negatives.
4792   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4793     if (FLL->isExact())
4794       return;
4795   } else
4796     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4797       if (FLR->isExact())
4798         return;
4799 
4800   // Check for comparisons with builtin types.
4801   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4802     if (CL->getBuiltinCallee())
4803       return;
4804 
4805   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4806     if (CR->getBuiltinCallee())
4807       return;
4808 
4809   // Emit the diagnostic.
4810   Diag(Loc, diag::warn_floatingpoint_eq)
4811     << LHS->getSourceRange() << RHS->getSourceRange();
4812 }
4813 
4814 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4815 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4816 
4817 namespace {
4818 
4819 /// Structure recording the 'active' range of an integer-valued
4820 /// expression.
4821 struct IntRange {
4822   /// The number of bits active in the int.
4823   unsigned Width;
4824 
4825   /// True if the int is known not to have negative values.
4826   bool NonNegative;
4827 
4828   IntRange(unsigned Width, bool NonNegative)
4829     : Width(Width), NonNegative(NonNegative)
4830   {}
4831 
4832   /// Returns the range of the bool type.
4833   static IntRange forBoolType() {
4834     return IntRange(1, true);
4835   }
4836 
4837   /// Returns the range of an opaque value of the given integral type.
4838   static IntRange forValueOfType(ASTContext &C, QualType T) {
4839     return forValueOfCanonicalType(C,
4840                           T->getCanonicalTypeInternal().getTypePtr());
4841   }
4842 
4843   /// Returns the range of an opaque value of a canonical integral type.
4844   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4845     assert(T->isCanonicalUnqualified());
4846 
4847     if (const VectorType *VT = dyn_cast<VectorType>(T))
4848       T = VT->getElementType().getTypePtr();
4849     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4850       T = CT->getElementType().getTypePtr();
4851 
4852     // For enum types, use the known bit width of the enumerators.
4853     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4854       EnumDecl *Enum = ET->getDecl();
4855       if (!Enum->isCompleteDefinition())
4856         return IntRange(C.getIntWidth(QualType(T, 0)), false);
4857 
4858       unsigned NumPositive = Enum->getNumPositiveBits();
4859       unsigned NumNegative = Enum->getNumNegativeBits();
4860 
4861       if (NumNegative == 0)
4862         return IntRange(NumPositive, true/*NonNegative*/);
4863       else
4864         return IntRange(std::max(NumPositive + 1, NumNegative),
4865                         false/*NonNegative*/);
4866     }
4867 
4868     const BuiltinType *BT = cast<BuiltinType>(T);
4869     assert(BT->isInteger());
4870 
4871     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4872   }
4873 
4874   /// Returns the "target" range of a canonical integral type, i.e.
4875   /// the range of values expressible in the type.
4876   ///
4877   /// This matches forValueOfCanonicalType except that enums have the
4878   /// full range of their type, not the range of their enumerators.
4879   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4880     assert(T->isCanonicalUnqualified());
4881 
4882     if (const VectorType *VT = dyn_cast<VectorType>(T))
4883       T = VT->getElementType().getTypePtr();
4884     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4885       T = CT->getElementType().getTypePtr();
4886     if (const EnumType *ET = dyn_cast<EnumType>(T))
4887       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4888 
4889     const BuiltinType *BT = cast<BuiltinType>(T);
4890     assert(BT->isInteger());
4891 
4892     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4893   }
4894 
4895   /// Returns the supremum of two ranges: i.e. their conservative merge.
4896   static IntRange join(IntRange L, IntRange R) {
4897     return IntRange(std::max(L.Width, R.Width),
4898                     L.NonNegative && R.NonNegative);
4899   }
4900 
4901   /// Returns the infinum of two ranges: i.e. their aggressive merge.
4902   static IntRange meet(IntRange L, IntRange R) {
4903     return IntRange(std::min(L.Width, R.Width),
4904                     L.NonNegative || R.NonNegative);
4905   }
4906 };
4907 
4908 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4909                               unsigned MaxWidth) {
4910   if (value.isSigned() && value.isNegative())
4911     return IntRange(value.getMinSignedBits(), false);
4912 
4913   if (value.getBitWidth() > MaxWidth)
4914     value = value.trunc(MaxWidth);
4915 
4916   // isNonNegative() just checks the sign bit without considering
4917   // signedness.
4918   return IntRange(value.getActiveBits(), true);
4919 }
4920 
4921 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4922                               unsigned MaxWidth) {
4923   if (result.isInt())
4924     return GetValueRange(C, result.getInt(), MaxWidth);
4925 
4926   if (result.isVector()) {
4927     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4928     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4929       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4930       R = IntRange::join(R, El);
4931     }
4932     return R;
4933   }
4934 
4935   if (result.isComplexInt()) {
4936     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4937     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4938     return IntRange::join(R, I);
4939   }
4940 
4941   // This can happen with lossless casts to intptr_t of "based" lvalues.
4942   // Assume it might use arbitrary bits.
4943   // FIXME: The only reason we need to pass the type in here is to get
4944   // the sign right on this one case.  It would be nice if APValue
4945   // preserved this.
4946   assert(result.isLValue() || result.isAddrLabelDiff());
4947   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4948 }
4949 
4950 static QualType GetExprType(Expr *E) {
4951   QualType Ty = E->getType();
4952   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4953     Ty = AtomicRHS->getValueType();
4954   return Ty;
4955 }
4956 
4957 /// Pseudo-evaluate the given integer expression, estimating the
4958 /// range of values it might take.
4959 ///
4960 /// \param MaxWidth - the width to which the value will be truncated
4961 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4962   E = E->IgnoreParens();
4963 
4964   // Try a full evaluation first.
4965   Expr::EvalResult result;
4966   if (E->EvaluateAsRValue(result, C))
4967     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4968 
4969   // I think we only want to look through implicit casts here; if the
4970   // user has an explicit widening cast, we should treat the value as
4971   // being of the new, wider type.
4972   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4973     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4974       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4975 
4976     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4977 
4978     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4979 
4980     // Assume that non-integer casts can span the full range of the type.
4981     if (!isIntegerCast)
4982       return OutputTypeRange;
4983 
4984     IntRange SubRange
4985       = GetExprRange(C, CE->getSubExpr(),
4986                      std::min(MaxWidth, OutputTypeRange.Width));
4987 
4988     // Bail out if the subexpr's range is as wide as the cast type.
4989     if (SubRange.Width >= OutputTypeRange.Width)
4990       return OutputTypeRange;
4991 
4992     // Otherwise, we take the smaller width, and we're non-negative if
4993     // either the output type or the subexpr is.
4994     return IntRange(SubRange.Width,
4995                     SubRange.NonNegative || OutputTypeRange.NonNegative);
4996   }
4997 
4998   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4999     // If we can fold the condition, just take that operand.
5000     bool CondResult;
5001     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5002       return GetExprRange(C, CondResult ? CO->getTrueExpr()
5003                                         : CO->getFalseExpr(),
5004                           MaxWidth);
5005 
5006     // Otherwise, conservatively merge.
5007     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5008     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5009     return IntRange::join(L, R);
5010   }
5011 
5012   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5013     switch (BO->getOpcode()) {
5014 
5015     // Boolean-valued operations are single-bit and positive.
5016     case BO_LAnd:
5017     case BO_LOr:
5018     case BO_LT:
5019     case BO_GT:
5020     case BO_LE:
5021     case BO_GE:
5022     case BO_EQ:
5023     case BO_NE:
5024       return IntRange::forBoolType();
5025 
5026     // The type of the assignments is the type of the LHS, so the RHS
5027     // is not necessarily the same type.
5028     case BO_MulAssign:
5029     case BO_DivAssign:
5030     case BO_RemAssign:
5031     case BO_AddAssign:
5032     case BO_SubAssign:
5033     case BO_XorAssign:
5034     case BO_OrAssign:
5035       // TODO: bitfields?
5036       return IntRange::forValueOfType(C, GetExprType(E));
5037 
5038     // Simple assignments just pass through the RHS, which will have
5039     // been coerced to the LHS type.
5040     case BO_Assign:
5041       // TODO: bitfields?
5042       return GetExprRange(C, BO->getRHS(), MaxWidth);
5043 
5044     // Operations with opaque sources are black-listed.
5045     case BO_PtrMemD:
5046     case BO_PtrMemI:
5047       return IntRange::forValueOfType(C, GetExprType(E));
5048 
5049     // Bitwise-and uses the *infinum* of the two source ranges.
5050     case BO_And:
5051     case BO_AndAssign:
5052       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5053                             GetExprRange(C, BO->getRHS(), MaxWidth));
5054 
5055     // Left shift gets black-listed based on a judgement call.
5056     case BO_Shl:
5057       // ...except that we want to treat '1 << (blah)' as logically
5058       // positive.  It's an important idiom.
5059       if (IntegerLiteral *I
5060             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5061         if (I->getValue() == 1) {
5062           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5063           return IntRange(R.Width, /*NonNegative*/ true);
5064         }
5065       }
5066       // fallthrough
5067 
5068     case BO_ShlAssign:
5069       return IntRange::forValueOfType(C, GetExprType(E));
5070 
5071     // Right shift by a constant can narrow its left argument.
5072     case BO_Shr:
5073     case BO_ShrAssign: {
5074       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5075 
5076       // If the shift amount is a positive constant, drop the width by
5077       // that much.
5078       llvm::APSInt shift;
5079       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5080           shift.isNonNegative()) {
5081         unsigned zext = shift.getZExtValue();
5082         if (zext >= L.Width)
5083           L.Width = (L.NonNegative ? 0 : 1);
5084         else
5085           L.Width -= zext;
5086       }
5087 
5088       return L;
5089     }
5090 
5091     // Comma acts as its right operand.
5092     case BO_Comma:
5093       return GetExprRange(C, BO->getRHS(), MaxWidth);
5094 
5095     // Black-list pointer subtractions.
5096     case BO_Sub:
5097       if (BO->getLHS()->getType()->isPointerType())
5098         return IntRange::forValueOfType(C, GetExprType(E));
5099       break;
5100 
5101     // The width of a division result is mostly determined by the size
5102     // of the LHS.
5103     case BO_Div: {
5104       // Don't 'pre-truncate' the operands.
5105       unsigned opWidth = C.getIntWidth(GetExprType(E));
5106       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5107 
5108       // If the divisor is constant, use that.
5109       llvm::APSInt divisor;
5110       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5111         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5112         if (log2 >= L.Width)
5113           L.Width = (L.NonNegative ? 0 : 1);
5114         else
5115           L.Width = std::min(L.Width - log2, MaxWidth);
5116         return L;
5117       }
5118 
5119       // Otherwise, just use the LHS's width.
5120       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5121       return IntRange(L.Width, L.NonNegative && R.NonNegative);
5122     }
5123 
5124     // The result of a remainder can't be larger than the result of
5125     // either side.
5126     case BO_Rem: {
5127       // Don't 'pre-truncate' the operands.
5128       unsigned opWidth = C.getIntWidth(GetExprType(E));
5129       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5130       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5131 
5132       IntRange meet = IntRange::meet(L, R);
5133       meet.Width = std::min(meet.Width, MaxWidth);
5134       return meet;
5135     }
5136 
5137     // The default behavior is okay for these.
5138     case BO_Mul:
5139     case BO_Add:
5140     case BO_Xor:
5141     case BO_Or:
5142       break;
5143     }
5144 
5145     // The default case is to treat the operation as if it were closed
5146     // on the narrowest type that encompasses both operands.
5147     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5148     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5149     return IntRange::join(L, R);
5150   }
5151 
5152   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5153     switch (UO->getOpcode()) {
5154     // Boolean-valued operations are white-listed.
5155     case UO_LNot:
5156       return IntRange::forBoolType();
5157 
5158     // Operations with opaque sources are black-listed.
5159     case UO_Deref:
5160     case UO_AddrOf: // should be impossible
5161       return IntRange::forValueOfType(C, GetExprType(E));
5162 
5163     default:
5164       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5165     }
5166   }
5167 
5168   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5169     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5170 
5171   if (FieldDecl *BitField = E->getSourceBitField())
5172     return IntRange(BitField->getBitWidthValue(C),
5173                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
5174 
5175   return IntRange::forValueOfType(C, GetExprType(E));
5176 }
5177 
5178 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5179   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5180 }
5181 
5182 /// Checks whether the given value, which currently has the given
5183 /// source semantics, has the same value when coerced through the
5184 /// target semantics.
5185 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5186                                  const llvm::fltSemantics &Src,
5187                                  const llvm::fltSemantics &Tgt) {
5188   llvm::APFloat truncated = value;
5189 
5190   bool ignored;
5191   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5192   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5193 
5194   return truncated.bitwiseIsEqual(value);
5195 }
5196 
5197 /// Checks whether the given value, which currently has the given
5198 /// source semantics, has the same value when coerced through the
5199 /// target semantics.
5200 ///
5201 /// The value might be a vector of floats (or a complex number).
5202 static bool IsSameFloatAfterCast(const APValue &value,
5203                                  const llvm::fltSemantics &Src,
5204                                  const llvm::fltSemantics &Tgt) {
5205   if (value.isFloat())
5206     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5207 
5208   if (value.isVector()) {
5209     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5210       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5211         return false;
5212     return true;
5213   }
5214 
5215   assert(value.isComplexFloat());
5216   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5217           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5218 }
5219 
5220 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5221 
5222 static bool IsZero(Sema &S, Expr *E) {
5223   // Suppress cases where we are comparing against an enum constant.
5224   if (const DeclRefExpr *DR =
5225       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5226     if (isa<EnumConstantDecl>(DR->getDecl()))
5227       return false;
5228 
5229   // Suppress cases where the '0' value is expanded from a macro.
5230   if (E->getLocStart().isMacroID())
5231     return false;
5232 
5233   llvm::APSInt Value;
5234   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5235 }
5236 
5237 static bool HasEnumType(Expr *E) {
5238   // Strip off implicit integral promotions.
5239   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5240     if (ICE->getCastKind() != CK_IntegralCast &&
5241         ICE->getCastKind() != CK_NoOp)
5242       break;
5243     E = ICE->getSubExpr();
5244   }
5245 
5246   return E->getType()->isEnumeralType();
5247 }
5248 
5249 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5250   // Disable warning in template instantiations.
5251   if (!S.ActiveTemplateInstantiations.empty())
5252     return;
5253 
5254   BinaryOperatorKind op = E->getOpcode();
5255   if (E->isValueDependent())
5256     return;
5257 
5258   if (op == BO_LT && IsZero(S, E->getRHS())) {
5259     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5260       << "< 0" << "false" << HasEnumType(E->getLHS())
5261       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5262   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5263     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5264       << ">= 0" << "true" << HasEnumType(E->getLHS())
5265       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5266   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5267     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5268       << "0 >" << "false" << HasEnumType(E->getRHS())
5269       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5270   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5271     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5272       << "0 <=" << "true" << HasEnumType(E->getRHS())
5273       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5274   }
5275 }
5276 
5277 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5278                                          Expr *Constant, Expr *Other,
5279                                          llvm::APSInt Value,
5280                                          bool RhsConstant) {
5281   // Disable warning in template instantiations.
5282   if (!S.ActiveTemplateInstantiations.empty())
5283     return;
5284 
5285   // 0 values are handled later by CheckTrivialUnsignedComparison().
5286   if (Value == 0)
5287     return;
5288 
5289   BinaryOperatorKind op = E->getOpcode();
5290   QualType OtherT = Other->getType();
5291   QualType ConstantT = Constant->getType();
5292   QualType CommonT = E->getLHS()->getType();
5293   if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5294     return;
5295   assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
5296          && "comparison with non-integer type");
5297 
5298   bool ConstantSigned = ConstantT->isSignedIntegerType();
5299   bool CommonSigned = CommonT->isSignedIntegerType();
5300 
5301   bool EqualityOnly = false;
5302 
5303   // TODO: Investigate using GetExprRange() to get tighter bounds on
5304   // on the bit ranges.
5305   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5306   unsigned OtherWidth = OtherRange.Width;
5307 
5308   if (CommonSigned) {
5309     // The common type is signed, therefore no signed to unsigned conversion.
5310     if (!OtherRange.NonNegative) {
5311       // Check that the constant is representable in type OtherT.
5312       if (ConstantSigned) {
5313         if (OtherWidth >= Value.getMinSignedBits())
5314           return;
5315       } else { // !ConstantSigned
5316         if (OtherWidth >= Value.getActiveBits() + 1)
5317           return;
5318       }
5319     } else { // !OtherSigned
5320       // Check that the constant is representable in type OtherT.
5321       // Negative values are out of range.
5322       if (ConstantSigned) {
5323         if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5324           return;
5325       } else { // !ConstantSigned
5326         if (OtherWidth >= Value.getActiveBits())
5327           return;
5328       }
5329     }
5330   } else {  // !CommonSigned
5331     if (OtherRange.NonNegative) {
5332       if (OtherWidth >= Value.getActiveBits())
5333         return;
5334     } else if (!OtherRange.NonNegative && !ConstantSigned) {
5335       // Check to see if the constant is representable in OtherT.
5336       if (OtherWidth > Value.getActiveBits())
5337         return;
5338       // Check to see if the constant is equivalent to a negative value
5339       // cast to CommonT.
5340       if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
5341           Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5342         return;
5343       // The constant value rests between values that OtherT can represent after
5344       // conversion.  Relational comparison still works, but equality
5345       // comparisons will be tautological.
5346       EqualityOnly = true;
5347     } else { // OtherSigned && ConstantSigned
5348       assert(0 && "Two signed types converted to unsigned types.");
5349     }
5350   }
5351 
5352   bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5353 
5354   bool IsTrue = true;
5355   if (op == BO_EQ || op == BO_NE) {
5356     IsTrue = op == BO_NE;
5357   } else if (EqualityOnly) {
5358     return;
5359   } else if (RhsConstant) {
5360     if (op == BO_GT || op == BO_GE)
5361       IsTrue = !PositiveConstant;
5362     else // op == BO_LT || op == BO_LE
5363       IsTrue = PositiveConstant;
5364   } else {
5365     if (op == BO_LT || op == BO_LE)
5366       IsTrue = !PositiveConstant;
5367     else // op == BO_GT || op == BO_GE
5368       IsTrue = PositiveConstant;
5369   }
5370 
5371   // If this is a comparison to an enum constant, include that
5372   // constant in the diagnostic.
5373   const EnumConstantDecl *ED = 0;
5374   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5375     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5376 
5377   SmallString<64> PrettySourceValue;
5378   llvm::raw_svector_ostream OS(PrettySourceValue);
5379   if (ED)
5380     OS << '\'' << *ED << "' (" << Value << ")";
5381   else
5382     OS << Value;
5383 
5384   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5385                         S.PDiag(diag::warn_out_of_range_compare)
5386                           << OS.str() << OtherT << IsTrue
5387                           << E->getLHS()->getSourceRange()
5388                           << E->getRHS()->getSourceRange());
5389 }
5390 
5391 /// Analyze the operands of the given comparison.  Implements the
5392 /// fallback case from AnalyzeComparison.
5393 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
5394   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5395   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5396 }
5397 
5398 /// \brief Implements -Wsign-compare.
5399 ///
5400 /// \param E the binary operator to check for warnings
5401 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
5402   // The type the comparison is being performed in.
5403   QualType T = E->getLHS()->getType();
5404   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5405          && "comparison with mismatched types");
5406   if (E->isValueDependent())
5407     return AnalyzeImpConvsInComparison(S, E);
5408 
5409   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5410   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
5411 
5412   bool IsComparisonConstant = false;
5413 
5414   // Check whether an integer constant comparison results in a value
5415   // of 'true' or 'false'.
5416   if (T->isIntegralType(S.Context)) {
5417     llvm::APSInt RHSValue;
5418     bool IsRHSIntegralLiteral =
5419       RHS->isIntegerConstantExpr(RHSValue, S.Context);
5420     llvm::APSInt LHSValue;
5421     bool IsLHSIntegralLiteral =
5422       LHS->isIntegerConstantExpr(LHSValue, S.Context);
5423     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5424         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5425     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5426       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5427     else
5428       IsComparisonConstant =
5429         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
5430   } else if (!T->hasUnsignedIntegerRepresentation())
5431       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
5432 
5433   // We don't do anything special if this isn't an unsigned integral
5434   // comparison:  we're only interested in integral comparisons, and
5435   // signed comparisons only happen in cases we don't care to warn about.
5436   //
5437   // We also don't care about value-dependent expressions or expressions
5438   // whose result is a constant.
5439   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
5440     return AnalyzeImpConvsInComparison(S, E);
5441 
5442   // Check to see if one of the (unmodified) operands is of different
5443   // signedness.
5444   Expr *signedOperand, *unsignedOperand;
5445   if (LHS->getType()->hasSignedIntegerRepresentation()) {
5446     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
5447            "unsigned comparison between two signed integer expressions?");
5448     signedOperand = LHS;
5449     unsignedOperand = RHS;
5450   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5451     signedOperand = RHS;
5452     unsignedOperand = LHS;
5453   } else {
5454     CheckTrivialUnsignedComparison(S, E);
5455     return AnalyzeImpConvsInComparison(S, E);
5456   }
5457 
5458   // Otherwise, calculate the effective range of the signed operand.
5459   IntRange signedRange = GetExprRange(S.Context, signedOperand);
5460 
5461   // Go ahead and analyze implicit conversions in the operands.  Note
5462   // that we skip the implicit conversions on both sides.
5463   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5464   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5465 
5466   // If the signed range is non-negative, -Wsign-compare won't fire,
5467   // but we should still check for comparisons which are always true
5468   // or false.
5469   if (signedRange.NonNegative)
5470     return CheckTrivialUnsignedComparison(S, E);
5471 
5472   // For (in)equality comparisons, if the unsigned operand is a
5473   // constant which cannot collide with a overflowed signed operand,
5474   // then reinterpreting the signed operand as unsigned will not
5475   // change the result of the comparison.
5476   if (E->isEqualityOp()) {
5477     unsigned comparisonWidth = S.Context.getIntWidth(T);
5478     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5479 
5480     // We should never be unable to prove that the unsigned operand is
5481     // non-negative.
5482     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5483 
5484     if (unsignedRange.Width < comparisonWidth)
5485       return;
5486   }
5487 
5488   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5489     S.PDiag(diag::warn_mixed_sign_comparison)
5490       << LHS->getType() << RHS->getType()
5491       << LHS->getSourceRange() << RHS->getSourceRange());
5492 }
5493 
5494 /// Analyzes an attempt to assign the given value to a bitfield.
5495 ///
5496 /// Returns true if there was something fishy about the attempt.
5497 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5498                                       SourceLocation InitLoc) {
5499   assert(Bitfield->isBitField());
5500   if (Bitfield->isInvalidDecl())
5501     return false;
5502 
5503   // White-list bool bitfields.
5504   if (Bitfield->getType()->isBooleanType())
5505     return false;
5506 
5507   // Ignore value- or type-dependent expressions.
5508   if (Bitfield->getBitWidth()->isValueDependent() ||
5509       Bitfield->getBitWidth()->isTypeDependent() ||
5510       Init->isValueDependent() ||
5511       Init->isTypeDependent())
5512     return false;
5513 
5514   Expr *OriginalInit = Init->IgnoreParenImpCasts();
5515 
5516   llvm::APSInt Value;
5517   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5518     return false;
5519 
5520   unsigned OriginalWidth = Value.getBitWidth();
5521   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5522 
5523   if (OriginalWidth <= FieldWidth)
5524     return false;
5525 
5526   // Compute the value which the bitfield will contain.
5527   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5528   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5529 
5530   // Check whether the stored value is equal to the original value.
5531   TruncatedValue = TruncatedValue.extend(OriginalWidth);
5532   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5533     return false;
5534 
5535   // Special-case bitfields of width 1: booleans are naturally 0/1, and
5536   // therefore don't strictly fit into a signed bitfield of width 1.
5537   if (FieldWidth == 1 && Value == 1)
5538     return false;
5539 
5540   std::string PrettyValue = Value.toString(10);
5541   std::string PrettyTrunc = TruncatedValue.toString(10);
5542 
5543   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5544     << PrettyValue << PrettyTrunc << OriginalInit->getType()
5545     << Init->getSourceRange();
5546 
5547   return true;
5548 }
5549 
5550 /// Analyze the given simple or compound assignment for warning-worthy
5551 /// operations.
5552 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5553   // Just recurse on the LHS.
5554   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5555 
5556   // We want to recurse on the RHS as normal unless we're assigning to
5557   // a bitfield.
5558   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5559     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5560                                   E->getOperatorLoc())) {
5561       // Recurse, ignoring any implicit conversions on the RHS.
5562       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5563                                         E->getOperatorLoc());
5564     }
5565   }
5566 
5567   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5568 }
5569 
5570 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5571 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5572                             SourceLocation CContext, unsigned diag,
5573                             bool pruneControlFlow = false) {
5574   if (pruneControlFlow) {
5575     S.DiagRuntimeBehavior(E->getExprLoc(), E,
5576                           S.PDiag(diag)
5577                             << SourceType << T << E->getSourceRange()
5578                             << SourceRange(CContext));
5579     return;
5580   }
5581   S.Diag(E->getExprLoc(), diag)
5582     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5583 }
5584 
5585 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5586 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5587                             SourceLocation CContext, unsigned diag,
5588                             bool pruneControlFlow = false) {
5589   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5590 }
5591 
5592 /// Diagnose an implicit cast from a literal expression. Does not warn when the
5593 /// cast wouldn't lose information.
5594 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5595                                     SourceLocation CContext) {
5596   // Try to convert the literal exactly to an integer. If we can, don't warn.
5597   bool isExact = false;
5598   const llvm::APFloat &Value = FL->getValue();
5599   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5600                             T->hasUnsignedIntegerRepresentation());
5601   if (Value.convertToInteger(IntegerValue,
5602                              llvm::APFloat::rmTowardZero, &isExact)
5603       == llvm::APFloat::opOK && isExact)
5604     return;
5605 
5606   // FIXME: Force the precision of the source value down so we don't print
5607   // digits which are usually useless (we don't really care here if we
5608   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
5609   // would automatically print the shortest representation, but it's a bit
5610   // tricky to implement.
5611   SmallString<16> PrettySourceValue;
5612   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5613   precision = (precision * 59 + 195) / 196;
5614   Value.toString(PrettySourceValue, precision);
5615 
5616   SmallString<16> PrettyTargetValue;
5617   if (T->isSpecificBuiltinType(BuiltinType::Bool))
5618     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5619   else
5620     IntegerValue.toString(PrettyTargetValue);
5621 
5622   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5623     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5624     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5625 }
5626 
5627 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5628   if (!Range.Width) return "0";
5629 
5630   llvm::APSInt ValueInRange = Value;
5631   ValueInRange.setIsSigned(!Range.NonNegative);
5632   ValueInRange = ValueInRange.trunc(Range.Width);
5633   return ValueInRange.toString(10);
5634 }
5635 
5636 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5637   if (!isa<ImplicitCastExpr>(Ex))
5638     return false;
5639 
5640   Expr *InnerE = Ex->IgnoreParenImpCasts();
5641   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5642   const Type *Source =
5643     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5644   if (Target->isDependentType())
5645     return false;
5646 
5647   const BuiltinType *FloatCandidateBT =
5648     dyn_cast<BuiltinType>(ToBool ? Source : Target);
5649   const Type *BoolCandidateType = ToBool ? Target : Source;
5650 
5651   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5652           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5653 }
5654 
5655 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5656                                       SourceLocation CC) {
5657   unsigned NumArgs = TheCall->getNumArgs();
5658   for (unsigned i = 0; i < NumArgs; ++i) {
5659     Expr *CurrA = TheCall->getArg(i);
5660     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5661       continue;
5662 
5663     bool IsSwapped = ((i > 0) &&
5664         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5665     IsSwapped |= ((i < (NumArgs - 1)) &&
5666         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5667     if (IsSwapped) {
5668       // Warn on this floating-point to bool conversion.
5669       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5670                       CurrA->getType(), CC,
5671                       diag::warn_impcast_floating_point_to_bool);
5672     }
5673   }
5674 }
5675 
5676 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5677                              SourceLocation CC, bool *ICContext = 0) {
5678   if (E->isTypeDependent() || E->isValueDependent()) return;
5679 
5680   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5681   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5682   if (Source == Target) return;
5683   if (Target->isDependentType()) return;
5684 
5685   // If the conversion context location is invalid don't complain. We also
5686   // don't want to emit a warning if the issue occurs from the expansion of
5687   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5688   // delay this check as long as possible. Once we detect we are in that
5689   // scenario, we just return.
5690   if (CC.isInvalid())
5691     return;
5692 
5693   // Diagnose implicit casts to bool.
5694   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5695     if (isa<StringLiteral>(E))
5696       // Warn on string literal to bool.  Checks for string literals in logical
5697       // and expressions, for instance, assert(0 && "error here"), are
5698       // prevented by a check in AnalyzeImplicitConversions().
5699       return DiagnoseImpCast(S, E, T, CC,
5700                              diag::warn_impcast_string_literal_to_bool);
5701     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5702         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5703       // This covers the literal expressions that evaluate to Objective-C
5704       // objects.
5705       return DiagnoseImpCast(S, E, T, CC,
5706                              diag::warn_impcast_objective_c_literal_to_bool);
5707     }
5708     if (Source->isPointerType() || Source->canDecayToPointerType()) {
5709       // Warn on pointer to bool conversion that is always true.
5710       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5711                                      SourceRange(CC));
5712     }
5713   }
5714 
5715   // Strip vector types.
5716   if (isa<VectorType>(Source)) {
5717     if (!isa<VectorType>(Target)) {
5718       if (S.SourceMgr.isInSystemMacro(CC))
5719         return;
5720       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5721     }
5722 
5723     // If the vector cast is cast between two vectors of the same size, it is
5724     // a bitcast, not a conversion.
5725     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5726       return;
5727 
5728     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5729     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5730   }
5731 
5732   // Strip complex types.
5733   if (isa<ComplexType>(Source)) {
5734     if (!isa<ComplexType>(Target)) {
5735       if (S.SourceMgr.isInSystemMacro(CC))
5736         return;
5737 
5738       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5739     }
5740 
5741     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5742     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5743   }
5744 
5745   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5746   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5747 
5748   // If the source is floating point...
5749   if (SourceBT && SourceBT->isFloatingPoint()) {
5750     // ...and the target is floating point...
5751     if (TargetBT && TargetBT->isFloatingPoint()) {
5752       // ...then warn if we're dropping FP rank.
5753 
5754       // Builtin FP kinds are ordered by increasing FP rank.
5755       if (SourceBT->getKind() > TargetBT->getKind()) {
5756         // Don't warn about float constants that are precisely
5757         // representable in the target type.
5758         Expr::EvalResult result;
5759         if (E->EvaluateAsRValue(result, S.Context)) {
5760           // Value might be a float, a float vector, or a float complex.
5761           if (IsSameFloatAfterCast(result.Val,
5762                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5763                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5764             return;
5765         }
5766 
5767         if (S.SourceMgr.isInSystemMacro(CC))
5768           return;
5769 
5770         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5771       }
5772       return;
5773     }
5774 
5775     // If the target is integral, always warn.
5776     if (TargetBT && TargetBT->isInteger()) {
5777       if (S.SourceMgr.isInSystemMacro(CC))
5778         return;
5779 
5780       Expr *InnerE = E->IgnoreParenImpCasts();
5781       // We also want to warn on, e.g., "int i = -1.234"
5782       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5783         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5784           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5785 
5786       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5787         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5788       } else {
5789         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5790       }
5791     }
5792 
5793     // If the target is bool, warn if expr is a function or method call.
5794     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5795         isa<CallExpr>(E)) {
5796       // Check last argument of function call to see if it is an
5797       // implicit cast from a type matching the type the result
5798       // is being cast to.
5799       CallExpr *CEx = cast<CallExpr>(E);
5800       unsigned NumArgs = CEx->getNumArgs();
5801       if (NumArgs > 0) {
5802         Expr *LastA = CEx->getArg(NumArgs - 1);
5803         Expr *InnerE = LastA->IgnoreParenImpCasts();
5804         const Type *InnerType =
5805           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5806         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5807           // Warn on this floating-point to bool conversion
5808           DiagnoseImpCast(S, E, T, CC,
5809                           diag::warn_impcast_floating_point_to_bool);
5810         }
5811       }
5812     }
5813     return;
5814   }
5815 
5816   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5817            == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5818       && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5819       && Target->isScalarType() && !Target->isNullPtrType()) {
5820     SourceLocation Loc = E->getSourceRange().getBegin();
5821     if (Loc.isMacroID())
5822       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5823     if (!Loc.isMacroID() || CC.isMacroID())
5824       S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5825           << T << clang::SourceRange(CC)
5826           << FixItHint::CreateReplacement(Loc,
5827                                           S.getFixItZeroLiteralForType(T, Loc));
5828   }
5829 
5830   if (!Source->isIntegerType() || !Target->isIntegerType())
5831     return;
5832 
5833   // TODO: remove this early return once the false positives for constant->bool
5834   // in templates, macros, etc, are reduced or removed.
5835   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5836     return;
5837 
5838   IntRange SourceRange = GetExprRange(S.Context, E);
5839   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5840 
5841   if (SourceRange.Width > TargetRange.Width) {
5842     // If the source is a constant, use a default-on diagnostic.
5843     // TODO: this should happen for bitfield stores, too.
5844     llvm::APSInt Value(32);
5845     if (E->isIntegerConstantExpr(Value, S.Context)) {
5846       if (S.SourceMgr.isInSystemMacro(CC))
5847         return;
5848 
5849       std::string PrettySourceValue = Value.toString(10);
5850       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5851 
5852       S.DiagRuntimeBehavior(E->getExprLoc(), E,
5853         S.PDiag(diag::warn_impcast_integer_precision_constant)
5854             << PrettySourceValue << PrettyTargetValue
5855             << E->getType() << T << E->getSourceRange()
5856             << clang::SourceRange(CC));
5857       return;
5858     }
5859 
5860     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5861     if (S.SourceMgr.isInSystemMacro(CC))
5862       return;
5863 
5864     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5865       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5866                              /* pruneControlFlow */ true);
5867     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5868   }
5869 
5870   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5871       (!TargetRange.NonNegative && SourceRange.NonNegative &&
5872        SourceRange.Width == TargetRange.Width)) {
5873 
5874     if (S.SourceMgr.isInSystemMacro(CC))
5875       return;
5876 
5877     unsigned DiagID = diag::warn_impcast_integer_sign;
5878 
5879     // Traditionally, gcc has warned about this under -Wsign-compare.
5880     // We also want to warn about it in -Wconversion.
5881     // So if -Wconversion is off, use a completely identical diagnostic
5882     // in the sign-compare group.
5883     // The conditional-checking code will
5884     if (ICContext) {
5885       DiagID = diag::warn_impcast_integer_sign_conditional;
5886       *ICContext = true;
5887     }
5888 
5889     return DiagnoseImpCast(S, E, T, CC, DiagID);
5890   }
5891 
5892   // Diagnose conversions between different enumeration types.
5893   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5894   // type, to give us better diagnostics.
5895   QualType SourceType = E->getType();
5896   if (!S.getLangOpts().CPlusPlus) {
5897     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5898       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5899         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5900         SourceType = S.Context.getTypeDeclType(Enum);
5901         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5902       }
5903   }
5904 
5905   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5906     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5907       if (SourceEnum->getDecl()->hasNameForLinkage() &&
5908           TargetEnum->getDecl()->hasNameForLinkage() &&
5909           SourceEnum != TargetEnum) {
5910         if (S.SourceMgr.isInSystemMacro(CC))
5911           return;
5912 
5913         return DiagnoseImpCast(S, E, SourceType, T, CC,
5914                                diag::warn_impcast_different_enum_types);
5915       }
5916 
5917   return;
5918 }
5919 
5920 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5921                               SourceLocation CC, QualType T);
5922 
5923 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5924                              SourceLocation CC, bool &ICContext) {
5925   E = E->IgnoreParenImpCasts();
5926 
5927   if (isa<ConditionalOperator>(E))
5928     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5929 
5930   AnalyzeImplicitConversions(S, E, CC);
5931   if (E->getType() != T)
5932     return CheckImplicitConversion(S, E, T, CC, &ICContext);
5933   return;
5934 }
5935 
5936 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5937                               SourceLocation CC, QualType T) {
5938   AnalyzeImplicitConversions(S, E->getCond(), CC);
5939 
5940   bool Suspicious = false;
5941   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5942   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5943 
5944   // If -Wconversion would have warned about either of the candidates
5945   // for a signedness conversion to the context type...
5946   if (!Suspicious) return;
5947 
5948   // ...but it's currently ignored...
5949   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5950                                  CC))
5951     return;
5952 
5953   // ...then check whether it would have warned about either of the
5954   // candidates for a signedness conversion to the condition type.
5955   if (E->getType() == T) return;
5956 
5957   Suspicious = false;
5958   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5959                           E->getType(), CC, &Suspicious);
5960   if (!Suspicious)
5961     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5962                             E->getType(), CC, &Suspicious);
5963 }
5964 
5965 /// AnalyzeImplicitConversions - Find and report any interesting
5966 /// implicit conversions in the given expression.  There are a couple
5967 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
5968 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5969   QualType T = OrigE->getType();
5970   Expr *E = OrigE->IgnoreParenImpCasts();
5971 
5972   if (E->isTypeDependent() || E->isValueDependent())
5973     return;
5974 
5975   // For conditional operators, we analyze the arguments as if they
5976   // were being fed directly into the output.
5977   if (isa<ConditionalOperator>(E)) {
5978     ConditionalOperator *CO = cast<ConditionalOperator>(E);
5979     CheckConditionalOperator(S, CO, CC, T);
5980     return;
5981   }
5982 
5983   // Check implicit argument conversions for function calls.
5984   if (CallExpr *Call = dyn_cast<CallExpr>(E))
5985     CheckImplicitArgumentConversions(S, Call, CC);
5986 
5987   // Go ahead and check any implicit conversions we might have skipped.
5988   // The non-canonical typecheck is just an optimization;
5989   // CheckImplicitConversion will filter out dead implicit conversions.
5990   if (E->getType() != T)
5991     CheckImplicitConversion(S, E, T, CC);
5992 
5993   // Now continue drilling into this expression.
5994 
5995   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5996     if (POE->getResultExpr())
5997       E = POE->getResultExpr();
5998   }
5999 
6000   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6001     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6002 
6003   // Skip past explicit casts.
6004   if (isa<ExplicitCastExpr>(E)) {
6005     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6006     return AnalyzeImplicitConversions(S, E, CC);
6007   }
6008 
6009   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6010     // Do a somewhat different check with comparison operators.
6011     if (BO->isComparisonOp())
6012       return AnalyzeComparison(S, BO);
6013 
6014     // And with simple assignments.
6015     if (BO->getOpcode() == BO_Assign)
6016       return AnalyzeAssignment(S, BO);
6017   }
6018 
6019   // These break the otherwise-useful invariant below.  Fortunately,
6020   // we don't really need to recurse into them, because any internal
6021   // expressions should have been analyzed already when they were
6022   // built into statements.
6023   if (isa<StmtExpr>(E)) return;
6024 
6025   // Don't descend into unevaluated contexts.
6026   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6027 
6028   // Now just recurse over the expression's children.
6029   CC = E->getExprLoc();
6030   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6031   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6032   for (Stmt::child_range I = E->children(); I; ++I) {
6033     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6034     if (!ChildExpr)
6035       continue;
6036 
6037     if (IsLogicalAndOperator &&
6038         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6039       // Ignore checking string literals that are in logical and operators.
6040       // This is a common pattern for asserts.
6041       continue;
6042     AnalyzeImplicitConversions(S, ChildExpr, CC);
6043   }
6044 }
6045 
6046 } // end anonymous namespace
6047 
6048 enum {
6049   AddressOf,
6050   FunctionPointer,
6051   ArrayPointer
6052 };
6053 
6054 /// \brief Diagnose pointers that are always non-null.
6055 /// \param E the expression containing the pointer
6056 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6057 /// compared to a null pointer
6058 /// \param IsEqual True when the comparison is equal to a null pointer
6059 /// \param Range Extra SourceRange to highlight in the diagnostic
6060 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6061                                         Expr::NullPointerConstantKind NullKind,
6062                                         bool IsEqual, SourceRange Range) {
6063 
6064   // Don't warn inside macros.
6065   if (E->getExprLoc().isMacroID())
6066       return;
6067   E = E->IgnoreImpCasts();
6068 
6069   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6070 
6071   bool IsAddressOf = false;
6072 
6073   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6074     if (UO->getOpcode() != UO_AddrOf)
6075       return;
6076     IsAddressOf = true;
6077     E = UO->getSubExpr();
6078   }
6079 
6080   // Expect to find a single Decl.  Skip anything more complicated.
6081   ValueDecl *D = 0;
6082   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6083     D = R->getDecl();
6084   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6085     D = M->getMemberDecl();
6086   }
6087 
6088   // Weak Decls can be null.
6089   if (!D || D->isWeak())
6090     return;
6091 
6092   QualType T = D->getType();
6093   const bool IsArray = T->isArrayType();
6094   const bool IsFunction = T->isFunctionType();
6095 
6096   if (IsAddressOf) {
6097     // Address of function is used to silence the function warning.
6098     if (IsFunction)
6099       return;
6100     // Address of reference can be null.
6101     if (T->isReferenceType())
6102       return;
6103   }
6104 
6105   // Found nothing.
6106   if (!IsAddressOf && !IsFunction && !IsArray)
6107     return;
6108 
6109   // Pretty print the expression for the diagnostic.
6110   std::string Str;
6111   llvm::raw_string_ostream S(Str);
6112   E->printPretty(S, 0, getPrintingPolicy());
6113 
6114   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6115                               : diag::warn_impcast_pointer_to_bool;
6116   unsigned DiagType;
6117   if (IsAddressOf)
6118     DiagType = AddressOf;
6119   else if (IsFunction)
6120     DiagType = FunctionPointer;
6121   else if (IsArray)
6122     DiagType = ArrayPointer;
6123   else
6124     llvm_unreachable("Could not determine diagnostic.");
6125   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6126                                 << Range << IsEqual;
6127 
6128   if (!IsFunction)
6129     return;
6130 
6131   // Suggest '&' to silence the function warning.
6132   Diag(E->getExprLoc(), diag::note_function_warning_silence)
6133       << FixItHint::CreateInsertion(E->getLocStart(), "&");
6134 
6135   // Check to see if '()' fixit should be emitted.
6136   QualType ReturnType;
6137   UnresolvedSet<4> NonTemplateOverloads;
6138   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6139   if (ReturnType.isNull())
6140     return;
6141 
6142   if (IsCompare) {
6143     // There are two cases here.  If there is null constant, the only suggest
6144     // for a pointer return type.  If the null is 0, then suggest if the return
6145     // type is a pointer or an integer type.
6146     if (!ReturnType->isPointerType()) {
6147       if (NullKind == Expr::NPCK_ZeroExpression ||
6148           NullKind == Expr::NPCK_ZeroLiteral) {
6149         if (!ReturnType->isIntegerType())
6150           return;
6151       } else {
6152         return;
6153       }
6154     }
6155   } else { // !IsCompare
6156     // For function to bool, only suggest if the function pointer has bool
6157     // return type.
6158     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6159       return;
6160   }
6161   Diag(E->getExprLoc(), diag::note_function_to_function_call)
6162       << FixItHint::CreateInsertion(
6163              getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6164 }
6165 
6166 
6167 /// Diagnoses "dangerous" implicit conversions within the given
6168 /// expression (which is a full expression).  Implements -Wconversion
6169 /// and -Wsign-compare.
6170 ///
6171 /// \param CC the "context" location of the implicit conversion, i.e.
6172 ///   the most location of the syntactic entity requiring the implicit
6173 ///   conversion
6174 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6175   // Don't diagnose in unevaluated contexts.
6176   if (isUnevaluatedContext())
6177     return;
6178 
6179   // Don't diagnose for value- or type-dependent expressions.
6180   if (E->isTypeDependent() || E->isValueDependent())
6181     return;
6182 
6183   // Check for array bounds violations in cases where the check isn't triggered
6184   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6185   // ArraySubscriptExpr is on the RHS of a variable initialization.
6186   CheckArrayAccess(E);
6187 
6188   // This is not the right CC for (e.g.) a variable initialization.
6189   AnalyzeImplicitConversions(*this, E, CC);
6190 }
6191 
6192 /// Diagnose when expression is an integer constant expression and its evaluation
6193 /// results in integer overflow
6194 void Sema::CheckForIntOverflow (Expr *E) {
6195   if (isa<BinaryOperator>(E->IgnoreParens()))
6196     E->EvaluateForOverflow(Context);
6197 }
6198 
6199 namespace {
6200 /// \brief Visitor for expressions which looks for unsequenced operations on the
6201 /// same object.
6202 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
6203   typedef EvaluatedExprVisitor<SequenceChecker> Base;
6204 
6205   /// \brief A tree of sequenced regions within an expression. Two regions are
6206   /// unsequenced if one is an ancestor or a descendent of the other. When we
6207   /// finish processing an expression with sequencing, such as a comma
6208   /// expression, we fold its tree nodes into its parent, since they are
6209   /// unsequenced with respect to nodes we will visit later.
6210   class SequenceTree {
6211     struct Value {
6212       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6213       unsigned Parent : 31;
6214       bool Merged : 1;
6215     };
6216     SmallVector<Value, 8> Values;
6217 
6218   public:
6219     /// \brief A region within an expression which may be sequenced with respect
6220     /// to some other region.
6221     class Seq {
6222       explicit Seq(unsigned N) : Index(N) {}
6223       unsigned Index;
6224       friend class SequenceTree;
6225     public:
6226       Seq() : Index(0) {}
6227     };
6228 
6229     SequenceTree() { Values.push_back(Value(0)); }
6230     Seq root() const { return Seq(0); }
6231 
6232     /// \brief Create a new sequence of operations, which is an unsequenced
6233     /// subset of \p Parent. This sequence of operations is sequenced with
6234     /// respect to other children of \p Parent.
6235     Seq allocate(Seq Parent) {
6236       Values.push_back(Value(Parent.Index));
6237       return Seq(Values.size() - 1);
6238     }
6239 
6240     /// \brief Merge a sequence of operations into its parent.
6241     void merge(Seq S) {
6242       Values[S.Index].Merged = true;
6243     }
6244 
6245     /// \brief Determine whether two operations are unsequenced. This operation
6246     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6247     /// should have been merged into its parent as appropriate.
6248     bool isUnsequenced(Seq Cur, Seq Old) {
6249       unsigned C = representative(Cur.Index);
6250       unsigned Target = representative(Old.Index);
6251       while (C >= Target) {
6252         if (C == Target)
6253           return true;
6254         C = Values[C].Parent;
6255       }
6256       return false;
6257     }
6258 
6259   private:
6260     /// \brief Pick a representative for a sequence.
6261     unsigned representative(unsigned K) {
6262       if (Values[K].Merged)
6263         // Perform path compression as we go.
6264         return Values[K].Parent = representative(Values[K].Parent);
6265       return K;
6266     }
6267   };
6268 
6269   /// An object for which we can track unsequenced uses.
6270   typedef NamedDecl *Object;
6271 
6272   /// Different flavors of object usage which we track. We only track the
6273   /// least-sequenced usage of each kind.
6274   enum UsageKind {
6275     /// A read of an object. Multiple unsequenced reads are OK.
6276     UK_Use,
6277     /// A modification of an object which is sequenced before the value
6278     /// computation of the expression, such as ++n in C++.
6279     UK_ModAsValue,
6280     /// A modification of an object which is not sequenced before the value
6281     /// computation of the expression, such as n++.
6282     UK_ModAsSideEffect,
6283 
6284     UK_Count = UK_ModAsSideEffect + 1
6285   };
6286 
6287   struct Usage {
6288     Usage() : Use(0), Seq() {}
6289     Expr *Use;
6290     SequenceTree::Seq Seq;
6291   };
6292 
6293   struct UsageInfo {
6294     UsageInfo() : Diagnosed(false) {}
6295     Usage Uses[UK_Count];
6296     /// Have we issued a diagnostic for this variable already?
6297     bool Diagnosed;
6298   };
6299   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6300 
6301   Sema &SemaRef;
6302   /// Sequenced regions within the expression.
6303   SequenceTree Tree;
6304   /// Declaration modifications and references which we have seen.
6305   UsageInfoMap UsageMap;
6306   /// The region we are currently within.
6307   SequenceTree::Seq Region;
6308   /// Filled in with declarations which were modified as a side-effect
6309   /// (that is, post-increment operations).
6310   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
6311   /// Expressions to check later. We defer checking these to reduce
6312   /// stack usage.
6313   SmallVectorImpl<Expr *> &WorkList;
6314 
6315   /// RAII object wrapping the visitation of a sequenced subexpression of an
6316   /// expression. At the end of this process, the side-effects of the evaluation
6317   /// become sequenced with respect to the value computation of the result, so
6318   /// we downgrade any UK_ModAsSideEffect within the evaluation to
6319   /// UK_ModAsValue.
6320   struct SequencedSubexpression {
6321     SequencedSubexpression(SequenceChecker &Self)
6322       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6323       Self.ModAsSideEffect = &ModAsSideEffect;
6324     }
6325     ~SequencedSubexpression() {
6326       for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6327         UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6328         U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6329         Self.addUsage(U, ModAsSideEffect[I].first,
6330                       ModAsSideEffect[I].second.Use, UK_ModAsValue);
6331       }
6332       Self.ModAsSideEffect = OldModAsSideEffect;
6333     }
6334 
6335     SequenceChecker &Self;
6336     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6337     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
6338   };
6339 
6340   /// RAII object wrapping the visitation of a subexpression which we might
6341   /// choose to evaluate as a constant. If any subexpression is evaluated and
6342   /// found to be non-constant, this allows us to suppress the evaluation of
6343   /// the outer expression.
6344   class EvaluationTracker {
6345   public:
6346     EvaluationTracker(SequenceChecker &Self)
6347         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6348       Self.EvalTracker = this;
6349     }
6350     ~EvaluationTracker() {
6351       Self.EvalTracker = Prev;
6352       if (Prev)
6353         Prev->EvalOK &= EvalOK;
6354     }
6355 
6356     bool evaluate(const Expr *E, bool &Result) {
6357       if (!EvalOK || E->isValueDependent())
6358         return false;
6359       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6360       return EvalOK;
6361     }
6362 
6363   private:
6364     SequenceChecker &Self;
6365     EvaluationTracker *Prev;
6366     bool EvalOK;
6367   } *EvalTracker;
6368 
6369   /// \brief Find the object which is produced by the specified expression,
6370   /// if any.
6371   Object getObject(Expr *E, bool Mod) const {
6372     E = E->IgnoreParenCasts();
6373     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6374       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6375         return getObject(UO->getSubExpr(), Mod);
6376     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6377       if (BO->getOpcode() == BO_Comma)
6378         return getObject(BO->getRHS(), Mod);
6379       if (Mod && BO->isAssignmentOp())
6380         return getObject(BO->getLHS(), Mod);
6381     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6382       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6383       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6384         return ME->getMemberDecl();
6385     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6386       // FIXME: If this is a reference, map through to its value.
6387       return DRE->getDecl();
6388     return 0;
6389   }
6390 
6391   /// \brief Note that an object was modified or used by an expression.
6392   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6393     Usage &U = UI.Uses[UK];
6394     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6395       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6396         ModAsSideEffect->push_back(std::make_pair(O, U));
6397       U.Use = Ref;
6398       U.Seq = Region;
6399     }
6400   }
6401   /// \brief Check whether a modification or use conflicts with a prior usage.
6402   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6403                   bool IsModMod) {
6404     if (UI.Diagnosed)
6405       return;
6406 
6407     const Usage &U = UI.Uses[OtherKind];
6408     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6409       return;
6410 
6411     Expr *Mod = U.Use;
6412     Expr *ModOrUse = Ref;
6413     if (OtherKind == UK_Use)
6414       std::swap(Mod, ModOrUse);
6415 
6416     SemaRef.Diag(Mod->getExprLoc(),
6417                  IsModMod ? diag::warn_unsequenced_mod_mod
6418                           : diag::warn_unsequenced_mod_use)
6419       << O << SourceRange(ModOrUse->getExprLoc());
6420     UI.Diagnosed = true;
6421   }
6422 
6423   void notePreUse(Object O, Expr *Use) {
6424     UsageInfo &U = UsageMap[O];
6425     // Uses conflict with other modifications.
6426     checkUsage(O, U, Use, UK_ModAsValue, false);
6427   }
6428   void notePostUse(Object O, Expr *Use) {
6429     UsageInfo &U = UsageMap[O];
6430     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6431     addUsage(U, O, Use, UK_Use);
6432   }
6433 
6434   void notePreMod(Object O, Expr *Mod) {
6435     UsageInfo &U = UsageMap[O];
6436     // Modifications conflict with other modifications and with uses.
6437     checkUsage(O, U, Mod, UK_ModAsValue, true);
6438     checkUsage(O, U, Mod, UK_Use, false);
6439   }
6440   void notePostMod(Object O, Expr *Use, UsageKind UK) {
6441     UsageInfo &U = UsageMap[O];
6442     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6443     addUsage(U, O, Use, UK);
6444   }
6445 
6446 public:
6447   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6448       : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6449         WorkList(WorkList), EvalTracker(0) {
6450     Visit(E);
6451   }
6452 
6453   void VisitStmt(Stmt *S) {
6454     // Skip all statements which aren't expressions for now.
6455   }
6456 
6457   void VisitExpr(Expr *E) {
6458     // By default, just recurse to evaluated subexpressions.
6459     Base::VisitStmt(E);
6460   }
6461 
6462   void VisitCastExpr(CastExpr *E) {
6463     Object O = Object();
6464     if (E->getCastKind() == CK_LValueToRValue)
6465       O = getObject(E->getSubExpr(), false);
6466 
6467     if (O)
6468       notePreUse(O, E);
6469     VisitExpr(E);
6470     if (O)
6471       notePostUse(O, E);
6472   }
6473 
6474   void VisitBinComma(BinaryOperator *BO) {
6475     // C++11 [expr.comma]p1:
6476     //   Every value computation and side effect associated with the left
6477     //   expression is sequenced before every value computation and side
6478     //   effect associated with the right expression.
6479     SequenceTree::Seq LHS = Tree.allocate(Region);
6480     SequenceTree::Seq RHS = Tree.allocate(Region);
6481     SequenceTree::Seq OldRegion = Region;
6482 
6483     {
6484       SequencedSubexpression SeqLHS(*this);
6485       Region = LHS;
6486       Visit(BO->getLHS());
6487     }
6488 
6489     Region = RHS;
6490     Visit(BO->getRHS());
6491 
6492     Region = OldRegion;
6493 
6494     // Forget that LHS and RHS are sequenced. They are both unsequenced
6495     // with respect to other stuff.
6496     Tree.merge(LHS);
6497     Tree.merge(RHS);
6498   }
6499 
6500   void VisitBinAssign(BinaryOperator *BO) {
6501     // The modification is sequenced after the value computation of the LHS
6502     // and RHS, so check it before inspecting the operands and update the
6503     // map afterwards.
6504     Object O = getObject(BO->getLHS(), true);
6505     if (!O)
6506       return VisitExpr(BO);
6507 
6508     notePreMod(O, BO);
6509 
6510     // C++11 [expr.ass]p7:
6511     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6512     //   only once.
6513     //
6514     // Therefore, for a compound assignment operator, O is considered used
6515     // everywhere except within the evaluation of E1 itself.
6516     if (isa<CompoundAssignOperator>(BO))
6517       notePreUse(O, BO);
6518 
6519     Visit(BO->getLHS());
6520 
6521     if (isa<CompoundAssignOperator>(BO))
6522       notePostUse(O, BO);
6523 
6524     Visit(BO->getRHS());
6525 
6526     // C++11 [expr.ass]p1:
6527     //   the assignment is sequenced [...] before the value computation of the
6528     //   assignment expression.
6529     // C11 6.5.16/3 has no such rule.
6530     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6531                                                        : UK_ModAsSideEffect);
6532   }
6533   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6534     VisitBinAssign(CAO);
6535   }
6536 
6537   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6538   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6539   void VisitUnaryPreIncDec(UnaryOperator *UO) {
6540     Object O = getObject(UO->getSubExpr(), true);
6541     if (!O)
6542       return VisitExpr(UO);
6543 
6544     notePreMod(O, UO);
6545     Visit(UO->getSubExpr());
6546     // C++11 [expr.pre.incr]p1:
6547     //   the expression ++x is equivalent to x+=1
6548     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6549                                                        : UK_ModAsSideEffect);
6550   }
6551 
6552   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6553   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6554   void VisitUnaryPostIncDec(UnaryOperator *UO) {
6555     Object O = getObject(UO->getSubExpr(), true);
6556     if (!O)
6557       return VisitExpr(UO);
6558 
6559     notePreMod(O, UO);
6560     Visit(UO->getSubExpr());
6561     notePostMod(O, UO, UK_ModAsSideEffect);
6562   }
6563 
6564   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6565   void VisitBinLOr(BinaryOperator *BO) {
6566     // The side-effects of the LHS of an '&&' are sequenced before the
6567     // value computation of the RHS, and hence before the value computation
6568     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6569     // as if they were unconditionally sequenced.
6570     EvaluationTracker Eval(*this);
6571     {
6572       SequencedSubexpression Sequenced(*this);
6573       Visit(BO->getLHS());
6574     }
6575 
6576     bool Result;
6577     if (Eval.evaluate(BO->getLHS(), Result)) {
6578       if (!Result)
6579         Visit(BO->getRHS());
6580     } else {
6581       // Check for unsequenced operations in the RHS, treating it as an
6582       // entirely separate evaluation.
6583       //
6584       // FIXME: If there are operations in the RHS which are unsequenced
6585       // with respect to operations outside the RHS, and those operations
6586       // are unconditionally evaluated, diagnose them.
6587       WorkList.push_back(BO->getRHS());
6588     }
6589   }
6590   void VisitBinLAnd(BinaryOperator *BO) {
6591     EvaluationTracker Eval(*this);
6592     {
6593       SequencedSubexpression Sequenced(*this);
6594       Visit(BO->getLHS());
6595     }
6596 
6597     bool Result;
6598     if (Eval.evaluate(BO->getLHS(), Result)) {
6599       if (Result)
6600         Visit(BO->getRHS());
6601     } else {
6602       WorkList.push_back(BO->getRHS());
6603     }
6604   }
6605 
6606   // Only visit the condition, unless we can be sure which subexpression will
6607   // be chosen.
6608   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6609     EvaluationTracker Eval(*this);
6610     {
6611       SequencedSubexpression Sequenced(*this);
6612       Visit(CO->getCond());
6613     }
6614 
6615     bool Result;
6616     if (Eval.evaluate(CO->getCond(), Result))
6617       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6618     else {
6619       WorkList.push_back(CO->getTrueExpr());
6620       WorkList.push_back(CO->getFalseExpr());
6621     }
6622   }
6623 
6624   void VisitCallExpr(CallExpr *CE) {
6625     // C++11 [intro.execution]p15:
6626     //   When calling a function [...], every value computation and side effect
6627     //   associated with any argument expression, or with the postfix expression
6628     //   designating the called function, is sequenced before execution of every
6629     //   expression or statement in the body of the function [and thus before
6630     //   the value computation of its result].
6631     SequencedSubexpression Sequenced(*this);
6632     Base::VisitCallExpr(CE);
6633 
6634     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6635   }
6636 
6637   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6638     // This is a call, so all subexpressions are sequenced before the result.
6639     SequencedSubexpression Sequenced(*this);
6640 
6641     if (!CCE->isListInitialization())
6642       return VisitExpr(CCE);
6643 
6644     // In C++11, list initializations are sequenced.
6645     SmallVector<SequenceTree::Seq, 32> Elts;
6646     SequenceTree::Seq Parent = Region;
6647     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6648                                         E = CCE->arg_end();
6649          I != E; ++I) {
6650       Region = Tree.allocate(Parent);
6651       Elts.push_back(Region);
6652       Visit(*I);
6653     }
6654 
6655     // Forget that the initializers are sequenced.
6656     Region = Parent;
6657     for (unsigned I = 0; I < Elts.size(); ++I)
6658       Tree.merge(Elts[I]);
6659   }
6660 
6661   void VisitInitListExpr(InitListExpr *ILE) {
6662     if (!SemaRef.getLangOpts().CPlusPlus11)
6663       return VisitExpr(ILE);
6664 
6665     // In C++11, list initializations are sequenced.
6666     SmallVector<SequenceTree::Seq, 32> Elts;
6667     SequenceTree::Seq Parent = Region;
6668     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6669       Expr *E = ILE->getInit(I);
6670       if (!E) continue;
6671       Region = Tree.allocate(Parent);
6672       Elts.push_back(Region);
6673       Visit(E);
6674     }
6675 
6676     // Forget that the initializers are sequenced.
6677     Region = Parent;
6678     for (unsigned I = 0; I < Elts.size(); ++I)
6679       Tree.merge(Elts[I]);
6680   }
6681 };
6682 }
6683 
6684 void Sema::CheckUnsequencedOperations(Expr *E) {
6685   SmallVector<Expr *, 8> WorkList;
6686   WorkList.push_back(E);
6687   while (!WorkList.empty()) {
6688     Expr *Item = WorkList.pop_back_val();
6689     SequenceChecker(*this, Item, WorkList);
6690   }
6691 }
6692 
6693 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6694                               bool IsConstexpr) {
6695   CheckImplicitConversions(E, CheckLoc);
6696   CheckUnsequencedOperations(E);
6697   if (!IsConstexpr && !E->isValueDependent())
6698     CheckForIntOverflow(E);
6699 }
6700 
6701 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6702                                        FieldDecl *BitField,
6703                                        Expr *Init) {
6704   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6705 }
6706 
6707 /// CheckParmsForFunctionDef - Check that the parameters of the given
6708 /// function are appropriate for the definition of a function. This
6709 /// takes care of any checks that cannot be performed on the
6710 /// declaration itself, e.g., that the types of each of the function
6711 /// parameters are complete.
6712 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6713                                     ParmVarDecl *const *PEnd,
6714                                     bool CheckParameterNames) {
6715   bool HasInvalidParm = false;
6716   for (; P != PEnd; ++P) {
6717     ParmVarDecl *Param = *P;
6718 
6719     // C99 6.7.5.3p4: the parameters in a parameter type list in a
6720     // function declarator that is part of a function definition of
6721     // that function shall not have incomplete type.
6722     //
6723     // This is also C++ [dcl.fct]p6.
6724     if (!Param->isInvalidDecl() &&
6725         RequireCompleteType(Param->getLocation(), Param->getType(),
6726                             diag::err_typecheck_decl_incomplete_type)) {
6727       Param->setInvalidDecl();
6728       HasInvalidParm = true;
6729     }
6730 
6731     // C99 6.9.1p5: If the declarator includes a parameter type list, the
6732     // declaration of each parameter shall include an identifier.
6733     if (CheckParameterNames &&
6734         Param->getIdentifier() == 0 &&
6735         !Param->isImplicit() &&
6736         !getLangOpts().CPlusPlus)
6737       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6738 
6739     // C99 6.7.5.3p12:
6740     //   If the function declarator is not part of a definition of that
6741     //   function, parameters may have incomplete type and may use the [*]
6742     //   notation in their sequences of declarator specifiers to specify
6743     //   variable length array types.
6744     QualType PType = Param->getOriginalType();
6745     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6746       if (AT->getSizeModifier() == ArrayType::Star) {
6747         // FIXME: This diagnostic should point the '[*]' if source-location
6748         // information is added for it.
6749         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6750         break;
6751       }
6752       PType= AT->getElementType();
6753     }
6754 
6755     // MSVC destroys objects passed by value in the callee.  Therefore a
6756     // function definition which takes such a parameter must be able to call the
6757     // object's destructor.  However, we don't perform any direct access check
6758     // on the dtor.
6759     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6760                                        .getCXXABI()
6761                                        .areArgsDestroyedLeftToRightInCallee()) {
6762       if (!Param->isInvalidDecl()) {
6763         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6764           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6765           if (!ClassDecl->isInvalidDecl() &&
6766               !ClassDecl->hasIrrelevantDestructor() &&
6767               !ClassDecl->isDependentContext()) {
6768             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6769             MarkFunctionReferenced(Param->getLocation(), Destructor);
6770             DiagnoseUseOfDecl(Destructor, Param->getLocation());
6771           }
6772         }
6773       }
6774     }
6775   }
6776 
6777   return HasInvalidParm;
6778 }
6779 
6780 /// CheckCastAlign - Implements -Wcast-align, which warns when a
6781 /// pointer cast increases the alignment requirements.
6782 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6783   // This is actually a lot of work to potentially be doing on every
6784   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6785   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6786                                           TRange.getBegin())
6787         == DiagnosticsEngine::Ignored)
6788     return;
6789 
6790   // Ignore dependent types.
6791   if (T->isDependentType() || Op->getType()->isDependentType())
6792     return;
6793 
6794   // Require that the destination be a pointer type.
6795   const PointerType *DestPtr = T->getAs<PointerType>();
6796   if (!DestPtr) return;
6797 
6798   // If the destination has alignment 1, we're done.
6799   QualType DestPointee = DestPtr->getPointeeType();
6800   if (DestPointee->isIncompleteType()) return;
6801   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6802   if (DestAlign.isOne()) return;
6803 
6804   // Require that the source be a pointer type.
6805   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6806   if (!SrcPtr) return;
6807   QualType SrcPointee = SrcPtr->getPointeeType();
6808 
6809   // Whitelist casts from cv void*.  We already implicitly
6810   // whitelisted casts to cv void*, since they have alignment 1.
6811   // Also whitelist casts involving incomplete types, which implicitly
6812   // includes 'void'.
6813   if (SrcPointee->isIncompleteType()) return;
6814 
6815   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6816   if (SrcAlign >= DestAlign) return;
6817 
6818   Diag(TRange.getBegin(), diag::warn_cast_align)
6819     << Op->getType() << T
6820     << static_cast<unsigned>(SrcAlign.getQuantity())
6821     << static_cast<unsigned>(DestAlign.getQuantity())
6822     << TRange << Op->getSourceRange();
6823 }
6824 
6825 static const Type* getElementType(const Expr *BaseExpr) {
6826   const Type* EltType = BaseExpr->getType().getTypePtr();
6827   if (EltType->isAnyPointerType())
6828     return EltType->getPointeeType().getTypePtr();
6829   else if (EltType->isArrayType())
6830     return EltType->getBaseElementTypeUnsafe();
6831   return EltType;
6832 }
6833 
6834 /// \brief Check whether this array fits the idiom of a size-one tail padded
6835 /// array member of a struct.
6836 ///
6837 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
6838 /// commonly used to emulate flexible arrays in C89 code.
6839 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6840                                     const NamedDecl *ND) {
6841   if (Size != 1 || !ND) return false;
6842 
6843   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6844   if (!FD) return false;
6845 
6846   // Don't consider sizes resulting from macro expansions or template argument
6847   // substitution to form C89 tail-padded arrays.
6848 
6849   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6850   while (TInfo) {
6851     TypeLoc TL = TInfo->getTypeLoc();
6852     // Look through typedefs.
6853     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6854       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6855       TInfo = TDL->getTypeSourceInfo();
6856       continue;
6857     }
6858     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6859       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6860       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6861         return false;
6862     }
6863     break;
6864   }
6865 
6866   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6867   if (!RD) return false;
6868   if (RD->isUnion()) return false;
6869   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6870     if (!CRD->isStandardLayout()) return false;
6871   }
6872 
6873   // See if this is the last field decl in the record.
6874   const Decl *D = FD;
6875   while ((D = D->getNextDeclInContext()))
6876     if (isa<FieldDecl>(D))
6877       return false;
6878   return true;
6879 }
6880 
6881 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6882                             const ArraySubscriptExpr *ASE,
6883                             bool AllowOnePastEnd, bool IndexNegated) {
6884   IndexExpr = IndexExpr->IgnoreParenImpCasts();
6885   if (IndexExpr->isValueDependent())
6886     return;
6887 
6888   const Type *EffectiveType = getElementType(BaseExpr);
6889   BaseExpr = BaseExpr->IgnoreParenCasts();
6890   const ConstantArrayType *ArrayTy =
6891     Context.getAsConstantArrayType(BaseExpr->getType());
6892   if (!ArrayTy)
6893     return;
6894 
6895   llvm::APSInt index;
6896   if (!IndexExpr->EvaluateAsInt(index, Context))
6897     return;
6898   if (IndexNegated)
6899     index = -index;
6900 
6901   const NamedDecl *ND = NULL;
6902   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6903     ND = dyn_cast<NamedDecl>(DRE->getDecl());
6904   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6905     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6906 
6907   if (index.isUnsigned() || !index.isNegative()) {
6908     llvm::APInt size = ArrayTy->getSize();
6909     if (!size.isStrictlyPositive())
6910       return;
6911 
6912     const Type* BaseType = getElementType(BaseExpr);
6913     if (BaseType != EffectiveType) {
6914       // Make sure we're comparing apples to apples when comparing index to size
6915       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6916       uint64_t array_typesize = Context.getTypeSize(BaseType);
6917       // Handle ptrarith_typesize being zero, such as when casting to void*
6918       if (!ptrarith_typesize) ptrarith_typesize = 1;
6919       if (ptrarith_typesize != array_typesize) {
6920         // There's a cast to a different size type involved
6921         uint64_t ratio = array_typesize / ptrarith_typesize;
6922         // TODO: Be smarter about handling cases where array_typesize is not a
6923         // multiple of ptrarith_typesize
6924         if (ptrarith_typesize * ratio == array_typesize)
6925           size *= llvm::APInt(size.getBitWidth(), ratio);
6926       }
6927     }
6928 
6929     if (size.getBitWidth() > index.getBitWidth())
6930       index = index.zext(size.getBitWidth());
6931     else if (size.getBitWidth() < index.getBitWidth())
6932       size = size.zext(index.getBitWidth());
6933 
6934     // For array subscripting the index must be less than size, but for pointer
6935     // arithmetic also allow the index (offset) to be equal to size since
6936     // computing the next address after the end of the array is legal and
6937     // commonly done e.g. in C++ iterators and range-based for loops.
6938     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6939       return;
6940 
6941     // Also don't warn for arrays of size 1 which are members of some
6942     // structure. These are often used to approximate flexible arrays in C89
6943     // code.
6944     if (IsTailPaddedMemberArray(*this, size, ND))
6945       return;
6946 
6947     // Suppress the warning if the subscript expression (as identified by the
6948     // ']' location) and the index expression are both from macro expansions
6949     // within a system header.
6950     if (ASE) {
6951       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6952           ASE->getRBracketLoc());
6953       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6954         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6955             IndexExpr->getLocStart());
6956         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6957           return;
6958       }
6959     }
6960 
6961     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6962     if (ASE)
6963       DiagID = diag::warn_array_index_exceeds_bounds;
6964 
6965     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6966                         PDiag(DiagID) << index.toString(10, true)
6967                           << size.toString(10, true)
6968                           << (unsigned)size.getLimitedValue(~0U)
6969                           << IndexExpr->getSourceRange());
6970   } else {
6971     unsigned DiagID = diag::warn_array_index_precedes_bounds;
6972     if (!ASE) {
6973       DiagID = diag::warn_ptr_arith_precedes_bounds;
6974       if (index.isNegative()) index = -index;
6975     }
6976 
6977     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6978                         PDiag(DiagID) << index.toString(10, true)
6979                           << IndexExpr->getSourceRange());
6980   }
6981 
6982   if (!ND) {
6983     // Try harder to find a NamedDecl to point at in the note.
6984     while (const ArraySubscriptExpr *ASE =
6985            dyn_cast<ArraySubscriptExpr>(BaseExpr))
6986       BaseExpr = ASE->getBase()->IgnoreParenCasts();
6987     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6988       ND = dyn_cast<NamedDecl>(DRE->getDecl());
6989     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6990       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6991   }
6992 
6993   if (ND)
6994     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6995                         PDiag(diag::note_array_index_out_of_bounds)
6996                           << ND->getDeclName());
6997 }
6998 
6999 void Sema::CheckArrayAccess(const Expr *expr) {
7000   int AllowOnePastEnd = 0;
7001   while (expr) {
7002     expr = expr->IgnoreParenImpCasts();
7003     switch (expr->getStmtClass()) {
7004       case Stmt::ArraySubscriptExprClass: {
7005         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7006         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7007                          AllowOnePastEnd > 0);
7008         return;
7009       }
7010       case Stmt::UnaryOperatorClass: {
7011         // Only unwrap the * and & unary operators
7012         const UnaryOperator *UO = cast<UnaryOperator>(expr);
7013         expr = UO->getSubExpr();
7014         switch (UO->getOpcode()) {
7015           case UO_AddrOf:
7016             AllowOnePastEnd++;
7017             break;
7018           case UO_Deref:
7019             AllowOnePastEnd--;
7020             break;
7021           default:
7022             return;
7023         }
7024         break;
7025       }
7026       case Stmt::ConditionalOperatorClass: {
7027         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7028         if (const Expr *lhs = cond->getLHS())
7029           CheckArrayAccess(lhs);
7030         if (const Expr *rhs = cond->getRHS())
7031           CheckArrayAccess(rhs);
7032         return;
7033       }
7034       default:
7035         return;
7036     }
7037   }
7038 }
7039 
7040 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7041 
7042 namespace {
7043   struct RetainCycleOwner {
7044     RetainCycleOwner() : Variable(0), Indirect(false) {}
7045     VarDecl *Variable;
7046     SourceRange Range;
7047     SourceLocation Loc;
7048     bool Indirect;
7049 
7050     void setLocsFrom(Expr *e) {
7051       Loc = e->getExprLoc();
7052       Range = e->getSourceRange();
7053     }
7054   };
7055 }
7056 
7057 /// Consider whether capturing the given variable can possibly lead to
7058 /// a retain cycle.
7059 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7060   // In ARC, it's captured strongly iff the variable has __strong
7061   // lifetime.  In MRR, it's captured strongly if the variable is
7062   // __block and has an appropriate type.
7063   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7064     return false;
7065 
7066   owner.Variable = var;
7067   if (ref)
7068     owner.setLocsFrom(ref);
7069   return true;
7070 }
7071 
7072 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7073   while (true) {
7074     e = e->IgnoreParens();
7075     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7076       switch (cast->getCastKind()) {
7077       case CK_BitCast:
7078       case CK_LValueBitCast:
7079       case CK_LValueToRValue:
7080       case CK_ARCReclaimReturnedObject:
7081         e = cast->getSubExpr();
7082         continue;
7083 
7084       default:
7085         return false;
7086       }
7087     }
7088 
7089     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7090       ObjCIvarDecl *ivar = ref->getDecl();
7091       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7092         return false;
7093 
7094       // Try to find a retain cycle in the base.
7095       if (!findRetainCycleOwner(S, ref->getBase(), owner))
7096         return false;
7097 
7098       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7099       owner.Indirect = true;
7100       return true;
7101     }
7102 
7103     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7104       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7105       if (!var) return false;
7106       return considerVariable(var, ref, owner);
7107     }
7108 
7109     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7110       if (member->isArrow()) return false;
7111 
7112       // Don't count this as an indirect ownership.
7113       e = member->getBase();
7114       continue;
7115     }
7116 
7117     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7118       // Only pay attention to pseudo-objects on property references.
7119       ObjCPropertyRefExpr *pre
7120         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7121                                               ->IgnoreParens());
7122       if (!pre) return false;
7123       if (pre->isImplicitProperty()) return false;
7124       ObjCPropertyDecl *property = pre->getExplicitProperty();
7125       if (!property->isRetaining() &&
7126           !(property->getPropertyIvarDecl() &&
7127             property->getPropertyIvarDecl()->getType()
7128               .getObjCLifetime() == Qualifiers::OCL_Strong))
7129           return false;
7130 
7131       owner.Indirect = true;
7132       if (pre->isSuperReceiver()) {
7133         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7134         if (!owner.Variable)
7135           return false;
7136         owner.Loc = pre->getLocation();
7137         owner.Range = pre->getSourceRange();
7138         return true;
7139       }
7140       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7141                               ->getSourceExpr());
7142       continue;
7143     }
7144 
7145     // Array ivars?
7146 
7147     return false;
7148   }
7149 }
7150 
7151 namespace {
7152   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7153     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7154       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7155         Variable(variable), Capturer(0) {}
7156 
7157     VarDecl *Variable;
7158     Expr *Capturer;
7159 
7160     void VisitDeclRefExpr(DeclRefExpr *ref) {
7161       if (ref->getDecl() == Variable && !Capturer)
7162         Capturer = ref;
7163     }
7164 
7165     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7166       if (Capturer) return;
7167       Visit(ref->getBase());
7168       if (Capturer && ref->isFreeIvar())
7169         Capturer = ref;
7170     }
7171 
7172     void VisitBlockExpr(BlockExpr *block) {
7173       // Look inside nested blocks
7174       if (block->getBlockDecl()->capturesVariable(Variable))
7175         Visit(block->getBlockDecl()->getBody());
7176     }
7177 
7178     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7179       if (Capturer) return;
7180       if (OVE->getSourceExpr())
7181         Visit(OVE->getSourceExpr());
7182     }
7183   };
7184 }
7185 
7186 /// Check whether the given argument is a block which captures a
7187 /// variable.
7188 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7189   assert(owner.Variable && owner.Loc.isValid());
7190 
7191   e = e->IgnoreParenCasts();
7192 
7193   // Look through [^{...} copy] and Block_copy(^{...}).
7194   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7195     Selector Cmd = ME->getSelector();
7196     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7197       e = ME->getInstanceReceiver();
7198       if (!e)
7199         return 0;
7200       e = e->IgnoreParenCasts();
7201     }
7202   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7203     if (CE->getNumArgs() == 1) {
7204       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
7205       if (Fn) {
7206         const IdentifierInfo *FnI = Fn->getIdentifier();
7207         if (FnI && FnI->isStr("_Block_copy")) {
7208           e = CE->getArg(0)->IgnoreParenCasts();
7209         }
7210       }
7211     }
7212   }
7213 
7214   BlockExpr *block = dyn_cast<BlockExpr>(e);
7215   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7216     return 0;
7217 
7218   FindCaptureVisitor visitor(S.Context, owner.Variable);
7219   visitor.Visit(block->getBlockDecl()->getBody());
7220   return visitor.Capturer;
7221 }
7222 
7223 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7224                                 RetainCycleOwner &owner) {
7225   assert(capturer);
7226   assert(owner.Variable && owner.Loc.isValid());
7227 
7228   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7229     << owner.Variable << capturer->getSourceRange();
7230   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7231     << owner.Indirect << owner.Range;
7232 }
7233 
7234 /// Check for a keyword selector that starts with the word 'add' or
7235 /// 'set'.
7236 static bool isSetterLikeSelector(Selector sel) {
7237   if (sel.isUnarySelector()) return false;
7238 
7239   StringRef str = sel.getNameForSlot(0);
7240   while (!str.empty() && str.front() == '_') str = str.substr(1);
7241   if (str.startswith("set"))
7242     str = str.substr(3);
7243   else if (str.startswith("add")) {
7244     // Specially whitelist 'addOperationWithBlock:'.
7245     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7246       return false;
7247     str = str.substr(3);
7248   }
7249   else
7250     return false;
7251 
7252   if (str.empty()) return true;
7253   return !isLowercase(str.front());
7254 }
7255 
7256 /// Check a message send to see if it's likely to cause a retain cycle.
7257 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7258   // Only check instance methods whose selector looks like a setter.
7259   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7260     return;
7261 
7262   // Try to find a variable that the receiver is strongly owned by.
7263   RetainCycleOwner owner;
7264   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
7265     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
7266       return;
7267   } else {
7268     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7269     owner.Variable = getCurMethodDecl()->getSelfDecl();
7270     owner.Loc = msg->getSuperLoc();
7271     owner.Range = msg->getSuperLoc();
7272   }
7273 
7274   // Check whether the receiver is captured by any of the arguments.
7275   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7276     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7277       return diagnoseRetainCycle(*this, capturer, owner);
7278 }
7279 
7280 /// Check a property assign to see if it's likely to cause a retain cycle.
7281 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7282   RetainCycleOwner owner;
7283   if (!findRetainCycleOwner(*this, receiver, owner))
7284     return;
7285 
7286   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7287     diagnoseRetainCycle(*this, capturer, owner);
7288 }
7289 
7290 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7291   RetainCycleOwner Owner;
7292   if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7293     return;
7294 
7295   // Because we don't have an expression for the variable, we have to set the
7296   // location explicitly here.
7297   Owner.Loc = Var->getLocation();
7298   Owner.Range = Var->getSourceRange();
7299 
7300   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7301     diagnoseRetainCycle(*this, Capturer, Owner);
7302 }
7303 
7304 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7305                                      Expr *RHS, bool isProperty) {
7306   // Check if RHS is an Objective-C object literal, which also can get
7307   // immediately zapped in a weak reference.  Note that we explicitly
7308   // allow ObjCStringLiterals, since those are designed to never really die.
7309   RHS = RHS->IgnoreParenImpCasts();
7310 
7311   // This enum needs to match with the 'select' in
7312   // warn_objc_arc_literal_assign (off-by-1).
7313   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7314   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7315     return false;
7316 
7317   S.Diag(Loc, diag::warn_arc_literal_assign)
7318     << (unsigned) Kind
7319     << (isProperty ? 0 : 1)
7320     << RHS->getSourceRange();
7321 
7322   return true;
7323 }
7324 
7325 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7326                                     Qualifiers::ObjCLifetime LT,
7327                                     Expr *RHS, bool isProperty) {
7328   // Strip off any implicit cast added to get to the one ARC-specific.
7329   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7330     if (cast->getCastKind() == CK_ARCConsumeObject) {
7331       S.Diag(Loc, diag::warn_arc_retained_assign)
7332         << (LT == Qualifiers::OCL_ExplicitNone)
7333         << (isProperty ? 0 : 1)
7334         << RHS->getSourceRange();
7335       return true;
7336     }
7337     RHS = cast->getSubExpr();
7338   }
7339 
7340   if (LT == Qualifiers::OCL_Weak &&
7341       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7342     return true;
7343 
7344   return false;
7345 }
7346 
7347 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7348                               QualType LHS, Expr *RHS) {
7349   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7350 
7351   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7352     return false;
7353 
7354   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7355     return true;
7356 
7357   return false;
7358 }
7359 
7360 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7361                               Expr *LHS, Expr *RHS) {
7362   QualType LHSType;
7363   // PropertyRef on LHS type need be directly obtained from
7364   // its declaration as it has a PseudoType.
7365   ObjCPropertyRefExpr *PRE
7366     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7367   if (PRE && !PRE->isImplicitProperty()) {
7368     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7369     if (PD)
7370       LHSType = PD->getType();
7371   }
7372 
7373   if (LHSType.isNull())
7374     LHSType = LHS->getType();
7375 
7376   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7377 
7378   if (LT == Qualifiers::OCL_Weak) {
7379     DiagnosticsEngine::Level Level =
7380       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7381     if (Level != DiagnosticsEngine::Ignored)
7382       getCurFunction()->markSafeWeakUse(LHS);
7383   }
7384 
7385   if (checkUnsafeAssigns(Loc, LHSType, RHS))
7386     return;
7387 
7388   // FIXME. Check for other life times.
7389   if (LT != Qualifiers::OCL_None)
7390     return;
7391 
7392   if (PRE) {
7393     if (PRE->isImplicitProperty())
7394       return;
7395     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7396     if (!PD)
7397       return;
7398 
7399     unsigned Attributes = PD->getPropertyAttributes();
7400     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
7401       // when 'assign' attribute was not explicitly specified
7402       // by user, ignore it and rely on property type itself
7403       // for lifetime info.
7404       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7405       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7406           LHSType->isObjCRetainableType())
7407         return;
7408 
7409       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7410         if (cast->getCastKind() == CK_ARCConsumeObject) {
7411           Diag(Loc, diag::warn_arc_retained_property_assign)
7412           << RHS->getSourceRange();
7413           return;
7414         }
7415         RHS = cast->getSubExpr();
7416       }
7417     }
7418     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
7419       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7420         return;
7421     }
7422   }
7423 }
7424 
7425 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7426 
7427 namespace {
7428 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7429                                  SourceLocation StmtLoc,
7430                                  const NullStmt *Body) {
7431   // Do not warn if the body is a macro that expands to nothing, e.g:
7432   //
7433   // #define CALL(x)
7434   // if (condition)
7435   //   CALL(0);
7436   //
7437   if (Body->hasLeadingEmptyMacro())
7438     return false;
7439 
7440   // Get line numbers of statement and body.
7441   bool StmtLineInvalid;
7442   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7443                                                       &StmtLineInvalid);
7444   if (StmtLineInvalid)
7445     return false;
7446 
7447   bool BodyLineInvalid;
7448   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7449                                                       &BodyLineInvalid);
7450   if (BodyLineInvalid)
7451     return false;
7452 
7453   // Warn if null statement and body are on the same line.
7454   if (StmtLine != BodyLine)
7455     return false;
7456 
7457   return true;
7458 }
7459 } // Unnamed namespace
7460 
7461 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7462                                  const Stmt *Body,
7463                                  unsigned DiagID) {
7464   // Since this is a syntactic check, don't emit diagnostic for template
7465   // instantiations, this just adds noise.
7466   if (CurrentInstantiationScope)
7467     return;
7468 
7469   // The body should be a null statement.
7470   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7471   if (!NBody)
7472     return;
7473 
7474   // Do the usual checks.
7475   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7476     return;
7477 
7478   Diag(NBody->getSemiLoc(), DiagID);
7479   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7480 }
7481 
7482 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7483                                  const Stmt *PossibleBody) {
7484   assert(!CurrentInstantiationScope); // Ensured by caller
7485 
7486   SourceLocation StmtLoc;
7487   const Stmt *Body;
7488   unsigned DiagID;
7489   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7490     StmtLoc = FS->getRParenLoc();
7491     Body = FS->getBody();
7492     DiagID = diag::warn_empty_for_body;
7493   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7494     StmtLoc = WS->getCond()->getSourceRange().getEnd();
7495     Body = WS->getBody();
7496     DiagID = diag::warn_empty_while_body;
7497   } else
7498     return; // Neither `for' nor `while'.
7499 
7500   // The body should be a null statement.
7501   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7502   if (!NBody)
7503     return;
7504 
7505   // Skip expensive checks if diagnostic is disabled.
7506   if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7507           DiagnosticsEngine::Ignored)
7508     return;
7509 
7510   // Do the usual checks.
7511   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7512     return;
7513 
7514   // `for(...);' and `while(...);' are popular idioms, so in order to keep
7515   // noise level low, emit diagnostics only if for/while is followed by a
7516   // CompoundStmt, e.g.:
7517   //    for (int i = 0; i < n; i++);
7518   //    {
7519   //      a(i);
7520   //    }
7521   // or if for/while is followed by a statement with more indentation
7522   // than for/while itself:
7523   //    for (int i = 0; i < n; i++);
7524   //      a(i);
7525   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7526   if (!ProbableTypo) {
7527     bool BodyColInvalid;
7528     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7529                              PossibleBody->getLocStart(),
7530                              &BodyColInvalid);
7531     if (BodyColInvalid)
7532       return;
7533 
7534     bool StmtColInvalid;
7535     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7536                              S->getLocStart(),
7537                              &StmtColInvalid);
7538     if (StmtColInvalid)
7539       return;
7540 
7541     if (BodyCol > StmtCol)
7542       ProbableTypo = true;
7543   }
7544 
7545   if (ProbableTypo) {
7546     Diag(NBody->getSemiLoc(), DiagID);
7547     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7548   }
7549 }
7550 
7551 //===--- Layout compatibility ----------------------------------------------//
7552 
7553 namespace {
7554 
7555 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7556 
7557 /// \brief Check if two enumeration types are layout-compatible.
7558 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7559   // C++11 [dcl.enum] p8:
7560   // Two enumeration types are layout-compatible if they have the same
7561   // underlying type.
7562   return ED1->isComplete() && ED2->isComplete() &&
7563          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7564 }
7565 
7566 /// \brief Check if two fields are layout-compatible.
7567 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7568   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7569     return false;
7570 
7571   if (Field1->isBitField() != Field2->isBitField())
7572     return false;
7573 
7574   if (Field1->isBitField()) {
7575     // Make sure that the bit-fields are the same length.
7576     unsigned Bits1 = Field1->getBitWidthValue(C);
7577     unsigned Bits2 = Field2->getBitWidthValue(C);
7578 
7579     if (Bits1 != Bits2)
7580       return false;
7581   }
7582 
7583   return true;
7584 }
7585 
7586 /// \brief Check if two standard-layout structs are layout-compatible.
7587 /// (C++11 [class.mem] p17)
7588 bool isLayoutCompatibleStruct(ASTContext &C,
7589                               RecordDecl *RD1,
7590                               RecordDecl *RD2) {
7591   // If both records are C++ classes, check that base classes match.
7592   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7593     // If one of records is a CXXRecordDecl we are in C++ mode,
7594     // thus the other one is a CXXRecordDecl, too.
7595     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7596     // Check number of base classes.
7597     if (D1CXX->getNumBases() != D2CXX->getNumBases())
7598       return false;
7599 
7600     // Check the base classes.
7601     for (CXXRecordDecl::base_class_const_iterator
7602                Base1 = D1CXX->bases_begin(),
7603            BaseEnd1 = D1CXX->bases_end(),
7604               Base2 = D2CXX->bases_begin();
7605          Base1 != BaseEnd1;
7606          ++Base1, ++Base2) {
7607       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7608         return false;
7609     }
7610   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7611     // If only RD2 is a C++ class, it should have zero base classes.
7612     if (D2CXX->getNumBases() > 0)
7613       return false;
7614   }
7615 
7616   // Check the fields.
7617   RecordDecl::field_iterator Field2 = RD2->field_begin(),
7618                              Field2End = RD2->field_end(),
7619                              Field1 = RD1->field_begin(),
7620                              Field1End = RD1->field_end();
7621   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7622     if (!isLayoutCompatible(C, *Field1, *Field2))
7623       return false;
7624   }
7625   if (Field1 != Field1End || Field2 != Field2End)
7626     return false;
7627 
7628   return true;
7629 }
7630 
7631 /// \brief Check if two standard-layout unions are layout-compatible.
7632 /// (C++11 [class.mem] p18)
7633 bool isLayoutCompatibleUnion(ASTContext &C,
7634                              RecordDecl *RD1,
7635                              RecordDecl *RD2) {
7636   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7637   for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7638                                   Field2End = RD2->field_end();
7639        Field2 != Field2End; ++Field2) {
7640     UnmatchedFields.insert(*Field2);
7641   }
7642 
7643   for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7644                                   Field1End = RD1->field_end();
7645        Field1 != Field1End; ++Field1) {
7646     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7647         I = UnmatchedFields.begin(),
7648         E = UnmatchedFields.end();
7649 
7650     for ( ; I != E; ++I) {
7651       if (isLayoutCompatible(C, *Field1, *I)) {
7652         bool Result = UnmatchedFields.erase(*I);
7653         (void) Result;
7654         assert(Result);
7655         break;
7656       }
7657     }
7658     if (I == E)
7659       return false;
7660   }
7661 
7662   return UnmatchedFields.empty();
7663 }
7664 
7665 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7666   if (RD1->isUnion() != RD2->isUnion())
7667     return false;
7668 
7669   if (RD1->isUnion())
7670     return isLayoutCompatibleUnion(C, RD1, RD2);
7671   else
7672     return isLayoutCompatibleStruct(C, RD1, RD2);
7673 }
7674 
7675 /// \brief Check if two types are layout-compatible in C++11 sense.
7676 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7677   if (T1.isNull() || T2.isNull())
7678     return false;
7679 
7680   // C++11 [basic.types] p11:
7681   // If two types T1 and T2 are the same type, then T1 and T2 are
7682   // layout-compatible types.
7683   if (C.hasSameType(T1, T2))
7684     return true;
7685 
7686   T1 = T1.getCanonicalType().getUnqualifiedType();
7687   T2 = T2.getCanonicalType().getUnqualifiedType();
7688 
7689   const Type::TypeClass TC1 = T1->getTypeClass();
7690   const Type::TypeClass TC2 = T2->getTypeClass();
7691 
7692   if (TC1 != TC2)
7693     return false;
7694 
7695   if (TC1 == Type::Enum) {
7696     return isLayoutCompatible(C,
7697                               cast<EnumType>(T1)->getDecl(),
7698                               cast<EnumType>(T2)->getDecl());
7699   } else if (TC1 == Type::Record) {
7700     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7701       return false;
7702 
7703     return isLayoutCompatible(C,
7704                               cast<RecordType>(T1)->getDecl(),
7705                               cast<RecordType>(T2)->getDecl());
7706   }
7707 
7708   return false;
7709 }
7710 }
7711 
7712 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7713 
7714 namespace {
7715 /// \brief Given a type tag expression find the type tag itself.
7716 ///
7717 /// \param TypeExpr Type tag expression, as it appears in user's code.
7718 ///
7719 /// \param VD Declaration of an identifier that appears in a type tag.
7720 ///
7721 /// \param MagicValue Type tag magic value.
7722 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7723                      const ValueDecl **VD, uint64_t *MagicValue) {
7724   while(true) {
7725     if (!TypeExpr)
7726       return false;
7727 
7728     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7729 
7730     switch (TypeExpr->getStmtClass()) {
7731     case Stmt::UnaryOperatorClass: {
7732       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7733       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7734         TypeExpr = UO->getSubExpr();
7735         continue;
7736       }
7737       return false;
7738     }
7739 
7740     case Stmt::DeclRefExprClass: {
7741       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7742       *VD = DRE->getDecl();
7743       return true;
7744     }
7745 
7746     case Stmt::IntegerLiteralClass: {
7747       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7748       llvm::APInt MagicValueAPInt = IL->getValue();
7749       if (MagicValueAPInt.getActiveBits() <= 64) {
7750         *MagicValue = MagicValueAPInt.getZExtValue();
7751         return true;
7752       } else
7753         return false;
7754     }
7755 
7756     case Stmt::BinaryConditionalOperatorClass:
7757     case Stmt::ConditionalOperatorClass: {
7758       const AbstractConditionalOperator *ACO =
7759           cast<AbstractConditionalOperator>(TypeExpr);
7760       bool Result;
7761       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7762         if (Result)
7763           TypeExpr = ACO->getTrueExpr();
7764         else
7765           TypeExpr = ACO->getFalseExpr();
7766         continue;
7767       }
7768       return false;
7769     }
7770 
7771     case Stmt::BinaryOperatorClass: {
7772       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7773       if (BO->getOpcode() == BO_Comma) {
7774         TypeExpr = BO->getRHS();
7775         continue;
7776       }
7777       return false;
7778     }
7779 
7780     default:
7781       return false;
7782     }
7783   }
7784 }
7785 
7786 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
7787 ///
7788 /// \param TypeExpr Expression that specifies a type tag.
7789 ///
7790 /// \param MagicValues Registered magic values.
7791 ///
7792 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7793 ///        kind.
7794 ///
7795 /// \param TypeInfo Information about the corresponding C type.
7796 ///
7797 /// \returns true if the corresponding C type was found.
7798 bool GetMatchingCType(
7799         const IdentifierInfo *ArgumentKind,
7800         const Expr *TypeExpr, const ASTContext &Ctx,
7801         const llvm::DenseMap<Sema::TypeTagMagicValue,
7802                              Sema::TypeTagData> *MagicValues,
7803         bool &FoundWrongKind,
7804         Sema::TypeTagData &TypeInfo) {
7805   FoundWrongKind = false;
7806 
7807   // Variable declaration that has type_tag_for_datatype attribute.
7808   const ValueDecl *VD = NULL;
7809 
7810   uint64_t MagicValue;
7811 
7812   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7813     return false;
7814 
7815   if (VD) {
7816     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
7817       if (I->getArgumentKind() != ArgumentKind) {
7818         FoundWrongKind = true;
7819         return false;
7820       }
7821       TypeInfo.Type = I->getMatchingCType();
7822       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7823       TypeInfo.MustBeNull = I->getMustBeNull();
7824       return true;
7825     }
7826     return false;
7827   }
7828 
7829   if (!MagicValues)
7830     return false;
7831 
7832   llvm::DenseMap<Sema::TypeTagMagicValue,
7833                  Sema::TypeTagData>::const_iterator I =
7834       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7835   if (I == MagicValues->end())
7836     return false;
7837 
7838   TypeInfo = I->second;
7839   return true;
7840 }
7841 } // unnamed namespace
7842 
7843 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7844                                       uint64_t MagicValue, QualType Type,
7845                                       bool LayoutCompatible,
7846                                       bool MustBeNull) {
7847   if (!TypeTagForDatatypeMagicValues)
7848     TypeTagForDatatypeMagicValues.reset(
7849         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7850 
7851   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7852   (*TypeTagForDatatypeMagicValues)[Magic] =
7853       TypeTagData(Type, LayoutCompatible, MustBeNull);
7854 }
7855 
7856 namespace {
7857 bool IsSameCharType(QualType T1, QualType T2) {
7858   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7859   if (!BT1)
7860     return false;
7861 
7862   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7863   if (!BT2)
7864     return false;
7865 
7866   BuiltinType::Kind T1Kind = BT1->getKind();
7867   BuiltinType::Kind T2Kind = BT2->getKind();
7868 
7869   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
7870          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
7871          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7872          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7873 }
7874 } // unnamed namespace
7875 
7876 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7877                                     const Expr * const *ExprArgs) {
7878   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7879   bool IsPointerAttr = Attr->getIsPointer();
7880 
7881   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7882   bool FoundWrongKind;
7883   TypeTagData TypeInfo;
7884   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7885                         TypeTagForDatatypeMagicValues.get(),
7886                         FoundWrongKind, TypeInfo)) {
7887     if (FoundWrongKind)
7888       Diag(TypeTagExpr->getExprLoc(),
7889            diag::warn_type_tag_for_datatype_wrong_kind)
7890         << TypeTagExpr->getSourceRange();
7891     return;
7892   }
7893 
7894   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7895   if (IsPointerAttr) {
7896     // Skip implicit cast of pointer to `void *' (as a function argument).
7897     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7898       if (ICE->getType()->isVoidPointerType() &&
7899           ICE->getCastKind() == CK_BitCast)
7900         ArgumentExpr = ICE->getSubExpr();
7901   }
7902   QualType ArgumentType = ArgumentExpr->getType();
7903 
7904   // Passing a `void*' pointer shouldn't trigger a warning.
7905   if (IsPointerAttr && ArgumentType->isVoidPointerType())
7906     return;
7907 
7908   if (TypeInfo.MustBeNull) {
7909     // Type tag with matching void type requires a null pointer.
7910     if (!ArgumentExpr->isNullPointerConstant(Context,
7911                                              Expr::NPC_ValueDependentIsNotNull)) {
7912       Diag(ArgumentExpr->getExprLoc(),
7913            diag::warn_type_safety_null_pointer_required)
7914           << ArgumentKind->getName()
7915           << ArgumentExpr->getSourceRange()
7916           << TypeTagExpr->getSourceRange();
7917     }
7918     return;
7919   }
7920 
7921   QualType RequiredType = TypeInfo.Type;
7922   if (IsPointerAttr)
7923     RequiredType = Context.getPointerType(RequiredType);
7924 
7925   bool mismatch = false;
7926   if (!TypeInfo.LayoutCompatible) {
7927     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7928 
7929     // C++11 [basic.fundamental] p1:
7930     // Plain char, signed char, and unsigned char are three distinct types.
7931     //
7932     // But we treat plain `char' as equivalent to `signed char' or `unsigned
7933     // char' depending on the current char signedness mode.
7934     if (mismatch)
7935       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7936                                            RequiredType->getPointeeType())) ||
7937           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7938         mismatch = false;
7939   } else
7940     if (IsPointerAttr)
7941       mismatch = !isLayoutCompatible(Context,
7942                                      ArgumentType->getPointeeType(),
7943                                      RequiredType->getPointeeType());
7944     else
7945       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7946 
7947   if (mismatch)
7948     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7949         << ArgumentType << ArgumentKind
7950         << TypeInfo.LayoutCompatible << RequiredType
7951         << ArgumentExpr->getSourceRange()
7952         << TypeTagExpr->getSourceRange();
7953 }
7954 
7955