Merge remote-tracking branch 'origin/swift-3.1-branch' into stable
* origin/swift-3.1-branch:
Revert "Add support for __builtin_os_log_format[_buffer_size]"
Revert "test/CodeGen/builtins.c: reinstate #ifdef __x86_64__ around __builtin_longjmp"
Revert "Fix test on non-X86 platforms"
Revert "Fix handling of %% format specifier in os_log builtins."
Revert "Fix diagnostic format string for err_os_log_argument_to_big"
diff --git a/include/clang/Analysis/Analyses/FormatString.h b/include/clang/Analysis/Analyses/FormatString.h
index 6813da9..170cfad 100644
--- a/include/clang/Analysis/Analyses/FormatString.h
+++ b/include/clang/Analysis/Analyses/FormatString.h
@@ -122,13 +122,12 @@
public:
enum Kind {
InvalidSpecifier = 0,
- // C99 conversion specifiers.
+ // C99 conversion specifiers.
cArg,
dArg,
DArg, // Apple extension
iArg,
- IntArgBeg = dArg,
- IntArgEnd = iArg,
+ IntArgBeg = dArg, IntArgEnd = iArg,
oArg,
OArg, // Apple extension
@@ -136,8 +135,7 @@
UArg, // Apple extension
xArg,
XArg,
- UIntArgBeg = oArg,
- UIntArgEnd = XArg,
+ UIntArgBeg = oArg, UIntArgEnd = XArg,
fArg,
FArg,
@@ -147,8 +145,7 @@
GArg,
aArg,
AArg,
- DoubleArgBeg = fArg,
- DoubleArgEnd = AArg,
+ DoubleArgBeg = fArg, DoubleArgEnd = AArg,
sArg,
pArg,
@@ -167,9 +164,8 @@
ZArg, // MS extension
// Objective-C specific specifiers.
- ObjCObjArg, // '@'
- ObjCBeg = ObjCObjArg,
- ObjCEnd = ObjCObjArg,
+ ObjCObjArg, // '@'
+ ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg,
// FreeBSD kernel specific specifiers.
FreeBSDbArg,
@@ -178,15 +174,13 @@
FreeBSDyArg,
// GlibC specific specifiers.
- PrintErrno, // 'm'
+ PrintErrno, // 'm'
- PrintfConvBeg = ObjCObjArg,
- PrintfConvEnd = PrintErrno,
+ PrintfConvBeg = ObjCObjArg, PrintfConvEnd = PrintErrno,
// ** Scanf-specific **
ScanListArg, // '['
- ScanfConvBeg = ScanListArg,
- ScanfConvEnd = ScanListArg
+ ScanfConvBeg = ScanListArg, ScanfConvEnd = ScanListArg
};
ConversionSpecifier(bool isPrintf = true)
@@ -448,15 +442,15 @@
OptionalFlag HasAlternativeForm; // '#'
OptionalFlag HasLeadingZeroes; // '0'
OptionalFlag HasObjCTechnicalTerm; // '[tt]'
- OptionalFlag IsPrivate; // '{private}'
- OptionalFlag IsPublic; // '{public}'
+ OptionalFlag IsPrivate; // '{private}'
+ OptionalFlag IsPublic; // '{public}'
OptionalAmount Precision;
public:
- PrintfSpecifier()
- : FormatSpecifier(/* isPrintf = */ true), HasThousandsGrouping("'"),
- IsLeftJustified("-"), HasPlusPrefix("+"), HasSpacePrefix(" "),
- HasAlternativeForm("#"), HasLeadingZeroes("0"),
- HasObjCTechnicalTerm("tt"), IsPrivate("private"), IsPublic("public") {}
+ PrintfSpecifier() :
+ FormatSpecifier(/* isPrintf = */ true),
+ HasThousandsGrouping("'"), IsLeftJustified("-"), HasPlusPrefix("+"),
+ HasSpacePrefix(" "), HasAlternativeForm("#"), HasLeadingZeroes("0"),
+ HasObjCTechnicalTerm("tt"), IsPrivate("private"), IsPublic("public") {}
static PrintfSpecifier Parse(const char *beg, const char *end);
@@ -485,8 +479,12 @@
void setHasObjCTechnicalTerm(const char *position) {
HasObjCTechnicalTerm.setPosition(position);
}
- void setIsPrivate(const char *position) { IsPrivate.setPosition(position); }
- void setIsPublic(const char *position) { IsPublic.setPosition(position); }
+ void setIsPrivate(const char *position) {
+ IsPrivate.setPosition(position);
+ }
+ void setIsPublic(const char *position) {
+ IsPublic.setPosition(position);
+ }
void setUsesPositionalArg() { UsesPositionalArg = true; }
// Methods for querying the format specifier.
diff --git a/include/clang/Analysis/Analyses/OSLog.h b/include/clang/Analysis/Analyses/OSLog.h
index 1e60a23..084b079 100644
--- a/include/clang/Analysis/Analyses/OSLog.h
+++ b/include/clang/Analysis/Analyses/OSLog.h
@@ -31,8 +31,8 @@
ScalarKind = 0,
// The item is a count, which describes the length of the following item to
- // be copied. A count may only be followed by an item of kind StringKind,
- // WideStringKind, or PointerKind.
+ // be copied. A count may only be followed by an item of kind StringKind or
+ // PointerKind.
CountKind,
// The item is a pointer to a C string. If preceded by a count 'n',
@@ -45,14 +45,7 @@
// The item is a pointer to an Objective-C object. os_log() may retain the
// object for later processing.
- ObjCObjKind,
-
- // The item is a pointer to wide-char string.
- WideStringKind,
-
- // The item is corresponding to the '%m' format specifier, no value is
- // populated in the buffer and the runtime is loading the errno value.
- ErrnoKind
+ ObjCObjKind
};
enum {
@@ -72,23 +65,23 @@
public:
OSLogBufferItem(Kind kind, const Expr *expr, CharUnits size, unsigned flags)
- : TheKind(kind), TheExpr(expr), Size(size), Flags(flags) {}
+ : TheKind(kind), TheExpr(expr), Size(size), Flags(flags) {}
OSLogBufferItem(ASTContext &Ctx, CharUnits value, unsigned flags)
- : TheKind(CountKind), ConstValue(value),
- Size(Ctx.getTypeSizeInChars(Ctx.IntTy)), Flags(flags) {}
+ : TheKind(CountKind), ConstValue(value),
+ Size(Ctx.getTypeSizeInChars(Ctx.IntTy)), Flags(flags) {}
unsigned char getDescriptorByte() const {
unsigned char result = 0;
- if (getIsPrivate())
- result |= IsPrivate;
- if (getIsPublic())
- result |= IsPublic;
+ if (getIsPrivate()) result |= 0x01;
+ if (getIsPublic()) result |= 0x02;
result |= ((unsigned)getKind()) << 4;
return result;
}
- unsigned char getSizeByte() const { return size().getQuantity(); }
+ unsigned char getSizeByte() const {
+ return getSize().getQuantity();
+ }
Kind getKind() const { return TheKind; }
bool getIsPrivate() const { return (Flags & IsPrivate) != 0; }
@@ -96,51 +89,50 @@
const Expr *getExpr() const { return TheExpr; }
CharUnits getConstValue() const { return ConstValue; }
- CharUnits size() const { return Size; }
+ CharUnits getSize() const { return Size; }
};
class OSLogBufferLayout {
public:
SmallVector<OSLogBufferItem, 4> Items;
- enum Flags { HasPrivateItems = 1, HasNonScalarItems = 1 << 1 };
-
- CharUnits size() const {
+ CharUnits getSize() const {
CharUnits result;
result += CharUnits::fromQuantity(2); // summary byte, num-args byte
for (auto &item : Items) {
// descriptor byte, size byte
- result += item.size() + CharUnits::fromQuantity(2);
+ result += item.getSize() + CharUnits::fromQuantity(2);
}
return result;
}
- bool hasPrivateItems() const {
- return llvm::any_of(
- Items, [](const OSLogBufferItem &Item) { return Item.getIsPrivate(); });
+ bool getHasPrivateItems() const {
+ return std::any_of(Items.begin(), Items.end(),
+ [](const OSLogBufferItem &item) { return item.getIsPrivate(); });
}
- bool hasPublicItems() const {
- return llvm::any_of(
- Items, [](const OSLogBufferItem &Item) { return Item.getIsPublic(); });
+ bool getHasPublicItems() const {
+ return std::any_of(Items.begin(), Items.end(),
+ [](const OSLogBufferItem &item) { return item.getIsPublic(); });
}
- bool hasNonScalar() const {
- return llvm::any_of(Items, [](const OSLogBufferItem &Item) {
- return Item.getKind() != OSLogBufferItem::ScalarKind;
- });
+ bool getHasNonScalar() const {
+ return std::any_of(Items.begin(), Items.end(),
+ [](const OSLogBufferItem &item) {
+ return item.getKind() != OSLogBufferItem::ScalarKind;
+ });
}
unsigned char getSummaryByte() const {
unsigned char result = 0;
- if (hasPrivateItems())
- result |= HasPrivateItems;
- if (hasNonScalar())
- result |= HasNonScalarItems;
+ if (getHasPrivateItems()) result |= 0x01;
+ if (getHasNonScalar()) result |= 0x02;
return result;
}
- unsigned char getNumArgsByte() const { return Items.size(); }
+ unsigned char getNumArgsByte() const {
+ return Items.size();
+ }
};
// Given a call 'E' to one of the builtins __builtin_os_log_format() or
diff --git a/include/clang/Basic/Builtins.def b/include/clang/Basic/Builtins.def
index c0bf94d..2a37541 100644
--- a/include/clang/Basic/Builtins.def
+++ b/include/clang/Basic/Builtins.def
@@ -1280,6 +1280,9 @@
BUILTIN(__builtin_nontemporal_store, "v.", "t")
BUILTIN(__builtin_nontemporal_load, "v.", "t")
+// Builtins for os_log/os_trace
+BUILTIN(__builtin_os_log_format_buffer_size, "zcC*.", "p:0:nut")
+BUILTIN(__builtin_os_log_format, "v*v*cC*.", "p:0:nt")
// OpenCL v2.0 s6.13.16, s9.17.3.5 - Pipe functions.
// We need the generic prototype, since the packet type could be anything.
LANGBUILTIN(read_pipe, "i.", "tn", OCLC20_LANG)
@@ -1317,10 +1320,6 @@
LANGBUILTIN(to_local, "v*v*", "tn", OCLC20_LANG)
LANGBUILTIN(to_private, "v*v*", "tn", OCLC20_LANG)
-// Builtins for os_log/os_trace
-BUILTIN(__builtin_os_log_format_buffer_size, "zcC*.", "p:0:nut")
-BUILTIN(__builtin_os_log_format, "v*v*cC*.", "p:0:nt")
-
#undef BUILTIN
#undef LIBBUILTIN
#undef LANGBUILTIN
diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td
index 1122cbe..96fb938 100644
--- a/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7598,9 +7598,7 @@
def err_os_log_format_not_string_constant : Error<
"os_log() format argument is not a string constant">;
def err_os_log_argument_too_big : Error<
- "os_log() argument %0 is too big (%1 bytes, max %2)">;
-def warn_os_log_format_narg : Error<
- "os_log() '%%n' format specifier is not allowed">, DefaultError;
+ "os_log() argument %d is too big (%d bytes, max %d)">;
// Statements.
def err_continue_not_in_loop : Error<
diff --git a/lib/Analysis/FormatString.cpp b/lib/Analysis/FormatString.cpp
index 7c29c51..ca981d9 100644
--- a/lib/Analysis/FormatString.cpp
+++ b/lib/Analysis/FormatString.cpp
@@ -590,8 +590,7 @@
case cArg: return "c";
case sArg: return "s";
case pArg: return "p";
- case PArg:
- return "P";
+ case PArg: return "P";
case nArg: return "n";
case PercentArg: return "%";
case ScanListArg: return "[";
diff --git a/lib/Analysis/OSLog.cpp b/lib/Analysis/OSLog.cpp
index 0418388..b6e9c49 100644
--- a/lib/Analysis/OSLog.cpp
+++ b/lib/Analysis/OSLog.cpp
@@ -1,12 +1,24 @@
-// TODO: header template
+//===--- OSLog.cpp - Analysis of calls to os_log builtins -------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines APIs for determining the layout of the data buffer for
+// os_log() and os_trace().
+//
+//===----------------------------------------------------------------------===//
#include "clang/Analysis/Analyses/OSLog.h"
+#include "clang/Analysis/Analyses/FormatString.h"
+#include "clang/Basic/Builtins.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/ExprObjC.h"
-#include "clang/Analysis/Analyses/FormatString.h"
-#include "clang/Basic/Builtins.h"
#include "llvm/ADT/SmallBitVector.h"
using namespace clang;
@@ -16,75 +28,49 @@
using clang::analyze_os_log::OSLogBufferLayout;
class OSLogFormatStringHandler
- : public analyze_format_string::FormatStringHandler {
+ : public analyze_format_string::FormatStringHandler {
private:
- struct ArgData {
- const Expr *E = nullptr;
- Optional<OSLogBufferItem::Kind> Kind;
- Optional<unsigned> Size;
- unsigned char Flags = 0;
- };
- SmallVector<ArgData, 4> ArgsData;
ArrayRef<const Expr *> Args;
-
- OSLogBufferItem::Kind
- getKind(analyze_format_string::ConversionSpecifier::Kind K) {
- switch (K) {
- case clang::analyze_format_string::ConversionSpecifier::sArg: // "%s"
- return OSLogBufferItem::StringKind;
- case clang::analyze_format_string::ConversionSpecifier::SArg: // "%S"
- return OSLogBufferItem::WideStringKind;
- case clang::analyze_format_string::ConversionSpecifier::PArg: { // "%P"
- return OSLogBufferItem::PointerKind;
- case clang::analyze_format_string::ConversionSpecifier::ObjCObjArg: // "%@"
- return OSLogBufferItem::ObjCObjKind;
- case clang::analyze_format_string::ConversionSpecifier::PrintErrno: // "%m"
- return OSLogBufferItem::ErrnoKind;
- default:
- return OSLogBufferItem::ScalarKind;
- }
- }
- }
+ SmallVector<Optional<OSLogBufferItem::Kind>, 4> ArgKind;
+ SmallVector<Optional<unsigned>, 4> ArgSize;
+ SmallVector<unsigned char, 4> ArgFlags;
public:
- OSLogFormatStringHandler(ArrayRef<const Expr *> Args) : Args(Args) {
- ArgsData.reserve(Args.size());
- }
+ OSLogFormatStringHandler(ArrayRef<const Expr *> args)
+ : FormatStringHandler(), Args(args), ArgKind(args.size(), None),
+ ArgSize(args.size(), None), ArgFlags(args.size(), 0)
+ {}
virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
- const char *StartSpecifier,
- unsigned SpecifierLen) {
- if (!FS.consumesDataArgument() &&
- FS.getConversionSpecifier().getKind() !=
- clang::analyze_format_string::ConversionSpecifier::PrintErrno)
- return true;
+ const char *startSpecifier,
+ unsigned specifierLen) {
- ArgsData.emplace_back();
- unsigned ArgIndex = FS.getArgIndex();
- if (ArgIndex < Args.size())
- ArgsData.back().E = Args[ArgIndex];
+ // Cases to handle:
+ // * "%f", "%d"... scalar (assumed for anything that doesn't fit the below
+ // cases)
+ // * "%s" pointer to null-terminated string
+ // * "%.*s" strlen (arg), pointer to string
+ // * "%.16s" strlen (non-arg), pointer to string
+ // * "%.*P" len (arg), pointer to data
+ // * "%.16P" len (non-arg), pointer to data
+ // * "%@" pointer to objc object
- // First get the Kind
- ArgsData.back().Kind = getKind(FS.getConversionSpecifier().getKind());
- if (ArgsData.back().Kind != OSLogBufferItem::ErrnoKind &&
- !ArgsData.back().E) {
- // missing argument
- ArgsData.pop_back();
+ unsigned argIndex = FS.getArgIndex();
+ if (argIndex >= Args.size()) {
return false;
}
-
switch (FS.getConversionSpecifier().getKind()) {
- case clang::analyze_format_string::ConversionSpecifier::sArg: // "%s"
- case clang::analyze_format_string::ConversionSpecifier::SArg: { // "%S"
+ case clang::analyze_format_string::ConversionSpecifier::sArg: { // "%s"
+ ArgKind[argIndex] = OSLogBufferItem::StringKind;
auto &precision = FS.getPrecision();
switch (precision.getHowSpecified()) {
case clang::analyze_format_string::OptionalAmount::NotSpecified: // "%s"
break;
case clang::analyze_format_string::OptionalAmount::Constant: // "%.16s"
- ArgsData.back().Size = precision.getConstantAmount();
+ ArgSize[argIndex] = precision.getConstantAmount();
break;
case clang::analyze_format_string::OptionalAmount::Arg: // "%.*s"
- ArgsData.back().Kind = OSLogBufferItem::CountKind;
+ ArgKind[precision.getArgIndex()] = OSLogBufferItem::CountKind;
break;
case clang::analyze_format_string::OptionalAmount::Invalid:
return false;
@@ -92,58 +78,62 @@
break;
}
case clang::analyze_format_string::ConversionSpecifier::PArg: { // "%P"
+ ArgKind[argIndex] = OSLogBufferItem::PointerKind;
auto &precision = FS.getPrecision();
switch (precision.getHowSpecified()) {
case clang::analyze_format_string::OptionalAmount::NotSpecified: // "%P"
return false; // length must be supplied with pointer format specifier
case clang::analyze_format_string::OptionalAmount::Constant: // "%.16P"
- ArgsData.back().Size = precision.getConstantAmount();
+ ArgSize[argIndex] = precision.getConstantAmount();
break;
case clang::analyze_format_string::OptionalAmount::Arg: // "%.*P"
- ArgsData.back().Kind = OSLogBufferItem::CountKind;
+ ArgKind[precision.getArgIndex()] = OSLogBufferItem::CountKind;
break;
case clang::analyze_format_string::OptionalAmount::Invalid:
return false;
}
break;
}
+ case clang::analyze_format_string::ConversionSpecifier::ObjCObjArg: // "%@"
+ ArgKind[argIndex] = OSLogBufferItem::ObjCObjKind;
+ break;
default:
+ ArgKind[argIndex] = OSLogBufferItem::ScalarKind;
break;
}
if (FS.isPrivate()) {
- ArgsData.back().Flags |= OSLogBufferItem::IsPrivate;
+ ArgFlags[argIndex] |= OSLogBufferItem::IsPrivate;
}
if (FS.isPublic()) {
- ArgsData.back().Flags |= OSLogBufferItem::IsPublic;
+ ArgFlags[argIndex] |= OSLogBufferItem::IsPublic;
}
return true;
}
- void computeLayout(ASTContext &Ctx, OSLogBufferLayout &Layout) const {
- Layout.Items.clear();
- for (auto &Data : ArgsData) {
- if (Data.Size)
- Layout.Items.emplace_back(Ctx, CharUnits::fromQuantity(*Data.Size),
- Data.Flags);
- if (Data.Kind) {
- CharUnits Size;
- if (*Data.Kind == OSLogBufferItem::ErrnoKind)
- Size = CharUnits::Zero();
- else
- Size = Ctx.getTypeSizeInChars(Data.E->getType());
- Layout.Items.emplace_back(*Data.Kind, Data.E, Size, Data.Flags);
+ void computeLayout(ASTContext &Ctx, OSLogBufferLayout &layout) const {
+ layout.Items.clear();
+ for (unsigned i = 0; i < Args.size(); i++) {
+ const Expr *arg = Args[i];
+ if (ArgSize[i]) {
+ layout.Items.emplace_back(Ctx, CharUnits::fromQuantity(*ArgSize[i]),
+ ArgFlags[i]);
+ }
+ CharUnits size = Ctx.getTypeSizeInChars(arg->getType());
+ if (ArgKind[i]) {
+ layout.Items.emplace_back(*ArgKind[i], arg, size, ArgFlags[i]);
} else {
- auto Size = Ctx.getTypeSizeInChars(Data.E->getType());
- Layout.Items.emplace_back(OSLogBufferItem::ScalarKind, Data.E, Size,
- Data.Flags);
+ layout.Items.emplace_back(OSLogBufferItem::ScalarKind, arg, size,
+ ArgFlags[i]);
}
}
}
};
-bool clang::analyze_os_log::computeOSLogBufferLayout(
- ASTContext &Ctx, const CallExpr *E, OSLogBufferLayout &Layout) {
+bool clang::analyze_os_log::computeOSLogBufferLayout(ASTContext &Ctx,
+ const CallExpr *E,
+ OSLogBufferLayout &layout)
+{
ArrayRef<const Expr *> Args(E->getArgs(), E->getArgs() + E->getNumArgs());
const Expr *StringArg;
@@ -167,11 +157,11 @@
const StringLiteral *Lit = cast<StringLiteral>(StringArg->IgnoreParenCasts());
assert(Lit && (Lit->isAscii() || Lit->isUTF8()));
- StringRef Data = Lit->getString();
+ StringRef data = Lit->getString();
OSLogFormatStringHandler H(VarArgs);
- ParsePrintfString(H, Data.begin(), Data.end(), Ctx.getLangOpts(),
- Ctx.getTargetInfo(), /*isFreeBSDKPrintf*/ false);
+ ParsePrintfString(H, data.begin(), data.end(), Ctx.getLangOpts(),
+ Ctx.getTargetInfo(), /*isFreeBSDKPrintf*/false);
- H.computeLayout(Ctx, Layout);
+ H.computeLayout(Ctx, layout);
return true;
}
diff --git a/lib/Analysis/PrintfFormatString.cpp b/lib/Analysis/PrintfFormatString.cpp
index ed7193e..1966344 100644
--- a/lib/Analysis/PrintfFormatString.cpp
+++ b/lib/Analysis/PrintfFormatString.cpp
@@ -124,9 +124,7 @@
if (*I == '{') {
OSLogVisibilityFlagsStart = I++;
// Find the end of the modifier.
- while (I != E && *I != '}') {
- I++;
- }
+ while (I != E && *I != '}') { I++; }
if (I == E) {
if (Warn)
H.HandleIncompleteSpecifier(Start, E - Start);
@@ -138,11 +136,9 @@
// Just see if 'private' or 'public' is the first word. os_log itself will
// do any further parsing.
const char *P = OSLogVisibilityFlagsStart + 1;
- while (P < OSLogVisibilityFlagsEnd && isspace(*P))
- P++;
+ while (P < OSLogVisibilityFlagsEnd && isspace(*P)) P++;
const char *WordStart = P;
- while (P < OSLogVisibilityFlagsEnd && (isalnum(*P) || *P == '_'))
- P++;
+ while (P < OSLogVisibilityFlagsEnd && (isalnum(*P) || *P == '_')) P++;
const char *WordEnd = P;
StringRef Word(WordStart, WordEnd - WordStart);
if (Word == "private") {
@@ -287,9 +283,7 @@
case 'C': k = ConversionSpecifier::CArg; break;
case 'S': k = ConversionSpecifier::SArg; break;
// Apple extension for os_log
- case 'P':
- k = ConversionSpecifier::PArg;
- break;
+ case 'P': k = ConversionSpecifier::PArg; break;
// Objective-C.
case '@': k = ConversionSpecifier::ObjCObjArg; break;
// Glibc specific.
diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp
index 463cc5f..7945335 100644
--- a/lib/CodeGen/CGBuiltin.cpp
+++ b/lib/CodeGen/CGBuiltin.cpp
@@ -11,10 +11,9 @@
//
//===----------------------------------------------------------------------===//
+#include "CodeGenFunction.h"
#include "CGCXXABI.h"
#include "CGObjCRuntime.h"
-#include "CGOpenCLRuntime.h"
-#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "TargetInfo.h"
#include "clang/AST/ASTContext.h"
@@ -465,15 +464,14 @@
}
namespace {
-// ARC cleanup for __builtin_os_log_format
-struct CallObjCArcUse final : EHScopeStack::Cleanup {
- CallObjCArcUse(llvm::Value *object) : object(object) {}
- llvm::Value *object;
+ struct CallObjCArcUse final : EHScopeStack::Cleanup {
+ CallObjCArcUse(llvm::Value *object) : object(object) {}
+ llvm::Value *object;
- void Emit(CodeGenFunction &CGF, Flags flags) override {
- CGF.EmitARCIntrinsicUse(object);
- }
-};
+ void Emit(CodeGenFunction &CGF, Flags flags) override {
+ CGF.EmitARCIntrinsicUse(object);
+ }
+ };
}
RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD,
@@ -2070,6 +2068,76 @@
return RValue::get(llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy));
break;
}
+ case Builtin::BI__builtin_os_log_format: {
+ assert(E->getNumArgs() >= 2 &&
+ "__builtin_os_log_format takes at least 2 arguments");
+ analyze_os_log::OSLogBufferLayout Layout;
+ analyze_os_log::computeOSLogBufferLayout(CGM.getContext(), E, Layout);
+ Address BufAddr = EmitPointerWithAlignment(E->getArg(0));
+ // Ignore argument 1, the format string. It is not currently used.
+ CharUnits offset;
+ Builder.CreateStore(
+ Builder.getInt8(Layout.getSummaryByte()),
+ Builder.CreateConstByteGEP(BufAddr, offset++, "summary"));
+ Builder.CreateStore(
+ Builder.getInt8(Layout.getNumArgsByte()),
+ Builder.CreateConstByteGEP(BufAddr, offset++, "numArgs"));
+
+ llvm::SmallVector<llvm::Value *, 4> RetainableOperands;
+ for (const auto &item : Layout.Items) {
+ Builder.CreateStore(
+ Builder.getInt8(item.getDescriptorByte()),
+ Builder.CreateConstByteGEP(BufAddr, offset++, "argDescriptor"));
+ Builder.CreateStore(
+ Builder.getInt8(item.getSizeByte()),
+ Builder.CreateConstByteGEP(BufAddr, offset++, "argSize"));
+ Address addr = Builder.CreateConstByteGEP(BufAddr, offset);
+ if (const Expr *expr = item.getExpr()) {
+ addr = Builder.CreateElementBitCast(addr,
+ ConvertTypeForMem(expr->getType()));
+ // Check if this is a retainable type.
+ if (expr->getType()->isObjCRetainableType()) {
+ assert(getEvaluationKind(expr->getType()) == TEK_Scalar &&
+ "Only scalar can be a ObjC retainable type");
+ llvm::Value *SV = EmitScalarExpr(expr, /*Ignore*/ false);
+ RValue RV = RValue::get(SV);
+ LValue LV = MakeAddrLValue(addr, expr->getType());
+ EmitStoreThroughLValue(RV, LV);
+ // Check if the object is constant, if not, save it in
+ // RetainableOperands.
+ if (!isa<Constant>(SV))
+ RetainableOperands.push_back(SV);
+ } else {
+ EmitAnyExprToMem(expr, addr, Qualifiers(), /*isInit*/true);
+ }
+ } else {
+ addr = Builder.CreateElementBitCast(addr, Int32Ty);
+ Builder.CreateStore(
+ Builder.getInt32(item.getConstValue().getQuantity()), addr);
+ }
+ offset += item.getSize();
+ }
+
+ // Push a clang.arc.use cleanup for each object in RetainableOperands. The
+ // cleanup will cause the use to appear after the final log call, keeping
+ // the object valid while it’s held in the log buffer. Note that if there’s
+ // a release cleanup on the object, it will already be active; since
+ // cleanups are emitted in reverse order, the use will occur before the
+ // object is released.
+ if (!RetainableOperands.empty() && getLangOpts().ObjCAutoRefCount &&
+ CGM.getCodeGenOpts().OptimizationLevel != 0)
+ for (llvm::Value *object : RetainableOperands)
+ pushFullExprCleanup<CallObjCArcUse>(getARCCleanupKind(), object);
+
+ return RValue::get(BufAddr.getPointer());
+ }
+
+ case Builtin::BI__builtin_os_log_format_buffer_size: {
+ analyze_os_log::OSLogBufferLayout Layout;
+ analyze_os_log::computeOSLogBufferLayout(CGM.getContext(), E, Layout);
+ return RValue::get(ConstantInt::get(ConvertType(E->getType()),
+ Layout.getSize().getQuantity()));
+ }
// OpenCL v2.0 s6.13.16.2, Built-in pipe read and write functions
case Builtin::BIread_pipe:
@@ -2387,76 +2455,6 @@
// Fall through - it's already mapped to the intrinsic by GCCBuiltin.
break;
}
- case Builtin::BI__builtin_os_log_format: {
- assert(E->getNumArgs() >= 2 &&
- "__builtin_os_log_format takes at least 2 arguments");
- analyze_os_log::OSLogBufferLayout Layout;
- analyze_os_log::computeOSLogBufferLayout(CGM.getContext(), E, Layout);
- Address BufAddr = EmitPointerWithAlignment(E->getArg(0));
- // Ignore argument 1, the format string. It is not currently used.
- CharUnits Offset;
- Builder.CreateStore(
- Builder.getInt8(Layout.getSummaryByte()),
- Builder.CreateConstByteGEP(BufAddr, Offset++, "summary"));
- Builder.CreateStore(
- Builder.getInt8(Layout.getNumArgsByte()),
- Builder.CreateConstByteGEP(BufAddr, Offset++, "numArgs"));
-
- llvm::SmallVector<llvm::Value *, 4> RetainableOperands;
- for (const auto &Item : Layout.Items) {
- Builder.CreateStore(
- Builder.getInt8(Item.getDescriptorByte()),
- Builder.CreateConstByteGEP(BufAddr, Offset++, "argDescriptor"));
- Builder.CreateStore(
- Builder.getInt8(Item.getSizeByte()),
- Builder.CreateConstByteGEP(BufAddr, Offset++, "argSize"));
- Address Addr = Builder.CreateConstByteGEP(BufAddr, Offset);
- if (const Expr *TheExpr = Item.getExpr()) {
- Addr = Builder.CreateElementBitCast(
- Addr, ConvertTypeForMem(TheExpr->getType()));
- // Check if this is a retainable type.
- if (TheExpr->getType()->isObjCRetainableType()) {
- assert(getEvaluationKind(TheExpr->getType()) == TEK_Scalar &&
- "Only scalar can be a ObjC retainable type");
- llvm::Value *SV = EmitScalarExpr(TheExpr, /*Ignore*/ false);
- RValue RV = RValue::get(SV);
- LValue LV = MakeAddrLValue(Addr, TheExpr->getType());
- EmitStoreThroughLValue(RV, LV);
- // Check if the object is constant, if not, save it in
- // RetainableOperands.
- if (!isa<Constant>(SV))
- RetainableOperands.push_back(SV);
- } else {
- EmitAnyExprToMem(TheExpr, Addr, Qualifiers(), /*isInit*/ true);
- }
- } else {
- Addr = Builder.CreateElementBitCast(Addr, Int32Ty);
- Builder.CreateStore(
- Builder.getInt32(Item.getConstValue().getQuantity()), Addr);
- }
- Offset += Item.size();
- }
-
- // Push a clang.arc.use cleanup for each object in RetainableOperands. The
- // cleanup will cause the use to appear after the final log call, keeping
- // the object valid while it’s held in the log buffer. Note that if there’s
- // a release cleanup on the object, it will already be active; since
- // cleanups are emitted in reverse order, the use will occur before the
- // object is released.
- if (!RetainableOperands.empty() && getLangOpts().ObjCAutoRefCount &&
- CGM.getCodeGenOpts().OptimizationLevel != 0)
- for (llvm::Value *object : RetainableOperands)
- pushFullExprCleanup<CallObjCArcUse>(getARCCleanupKind(), object);
-
- return RValue::get(BufAddr.getPointer());
- }
-
- case Builtin::BI__builtin_os_log_format_buffer_size: {
- analyze_os_log::OSLogBufferLayout Layout;
- analyze_os_log::computeOSLogBufferLayout(CGM.getContext(), E, Layout);
- return RValue::get(ConstantInt::get(ConvertType(E->getType()),
- Layout.size().getQuantity()));
- }
}
// If this is an alias for a lib function (e.g. __builtin_sin), emit
diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp
index 08af0df..6759a61 100644
--- a/lib/Sema/SemaChecking.cpp
+++ b/lib/Sema/SemaChecking.cpp
@@ -1048,6 +1048,12 @@
if (SemaBuiltinPipePackets(*this, TheCall))
return ExprError();
break;
+ case Builtin::BI__builtin_os_log_format:
+ case Builtin::BI__builtin_os_log_format_buffer_size:
+ if (SemaBuiltinOSLogFormat(TheCall)) {
+ return ExprError();
+ }
+ break;
case Builtin::BIto_global:
case Builtin::BIto_local:
case Builtin::BIto_private:
@@ -1063,13 +1069,6 @@
case Builtin::BIget_kernel_preferred_work_group_size_multiple:
if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
return ExprError();
- break;
- case Builtin::BI__builtin_os_log_format:
- case Builtin::BI__builtin_os_log_format_buffer_size:
- if (SemaBuiltinOSLogFormat(TheCall)) {
- return ExprError();
- }
- break;
}
// Since the target specific builtins for each arch overlap, only check those
@@ -3177,7 +3176,7 @@
/// and os_trace() functions is correct, and converts it to const char *.
ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
Arg = Arg->IgnoreParenCasts();
- auto *Literal = dyn_cast<StringLiteral>(Arg);
+ StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
if (!Literal) {
if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
Literal = ObjcLiteral->getString();
@@ -3186,14 +3185,14 @@
if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
return ExprError(
- Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
+ Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
<< Arg->getSourceRange());
}
ExprResult Result(Literal);
QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
- InitializedEntity Entity =
- InitializedEntity::InitializeParameter(Context, ResultTy, false);
+ InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
+ ResultTy, false);
Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
return Result;
}
@@ -3645,32 +3644,32 @@
bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
unsigned BuiltinID =
- cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
+ cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
unsigned NumArgs = TheCall->getNumArgs();
unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
if (NumArgs < NumRequiredArgs) {
- return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
- << 0 /* function call */ << NumRequiredArgs << NumArgs
- << TheCall->getSourceRange();
+ return Diag(TheCall->getLocEnd(),
+ diag::err_typecheck_call_too_few_args)
+ << 0 /* function call */ << NumRequiredArgs << NumArgs
+ << TheCall->getSourceRange();
}
if (NumArgs >= NumRequiredArgs + 0x100) {
return Diag(TheCall->getLocEnd(),
diag::err_typecheck_call_too_many_args_at_most)
- << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
- << TheCall->getSourceRange();
+ << 0 /* function call */ << (NumRequiredArgs + 0xff)
+ << NumArgs << TheCall->getSourceRange();
}
unsigned i = 0;
// For formatting call, check buffer arg.
if (!IsSizeCall) {
ExprResult Arg(TheCall->getArg(i));
- InitializedEntity Entity = InitializedEntity::InitializeParameter(
- Context, Context.VoidPtrTy, false);
+ InitializedEntity Entity =
+ InitializedEntity::InitializeParameter(Context, Context.VoidPtrTy, false);
Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
- if (Arg.isInvalid())
- return true;
+ if (Arg.isInvalid()) return true;
TheCall->setArg(i, Arg.get());
i++;
}
@@ -3679,8 +3678,7 @@
unsigned FormatIdx = i;
{
ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
- if (Arg.isInvalid())
- return true;
+ if (Arg.isInvalid()) return true;
TheCall->setArg(i, Arg.get());
i++;
}
@@ -3688,15 +3686,16 @@
// Make sure variadic args are scalar.
unsigned FirstDataArg = i;
while (i < NumArgs) {
- ExprResult Arg = DefaultVariadicArgumentPromotion(
- TheCall->getArg(i), VariadicFunction, nullptr);
- if (Arg.isInvalid())
- return true;
+ ExprResult Arg = DefaultVariadicArgumentPromotion(TheCall->getArg(i),
+ VariadicFunction,
+ nullptr);
+ if (Arg.isInvalid()) return true;
CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
if (ArgSize.getQuantity() >= 0x100) {
- return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
- << i << (int)ArgSize.getQuantity() << 0xff
- << TheCall->getSourceRange();
+ return Diag(Arg.get()->getLocEnd(),
+ diag::err_os_log_argument_too_big)
+ << i << (int)ArgSize.getQuantity() << 0xff
+ << TheCall->getSourceRange();
}
TheCall->setArg(i, Arg.get());
i++;
@@ -3707,12 +3706,12 @@
if (!IsSizeCall) {
llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
- bool Success = CheckFormatArguments(
- Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
- VariadicFunction, TheCall->getLocStart(), SourceRange(),
- CheckedVarArgs);
- if (!Success)
- return true;
+ bool Success = CheckFormatArguments(Args, /*HasVAListArg*/false, FormatIdx,
+ FirstDataArg, FST_OSLog,
+ VariadicFunction,
+ TheCall->getLocStart(), SourceRange(),
+ CheckedVarArgs);
+ if (!Success) return true;
}
if (IsSizeCall) {
@@ -4171,16 +4170,16 @@
Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
- .Case("scanf", FST_Scanf)
- .Cases("printf", "printf0", FST_Printf)
- .Cases("NSString", "CFString", FST_NSString)
- .Case("strftime", FST_Strftime)
- .Case("strfmon", FST_Strfmon)
- .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
- .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
- .Case("os_trace", FST_OSLog)
- .Case("os_log", FST_OSLog)
- .Default(FST_Unknown);
+ .Case("scanf", FST_Scanf)
+ .Cases("printf", "printf0", FST_Printf)
+ .Cases("NSString", "CFString", FST_NSString)
+ .Case("strftime", FST_Strftime)
+ .Case("strfmon", FST_Strfmon)
+ .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
+ .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
+ .Case("os_trace", FST_OSLog)
+ .Case("os_log", FST_OSLog)
+ .Default(FST_Unknown);
}
/// CheckFormatArguments - Check calls to printf and scanf (and similar
@@ -4309,16 +4308,18 @@
const Expr *origFormatExpr,
const Sema::FormatStringType type, unsigned firstDataArg,
unsigned numDataArgs, const char *beg, bool hasVAListArg,
- ArrayRef<const Expr *> Args, unsigned formatIdx,
- bool inFunctionCall, Sema::VariadicCallType callType,
+ ArrayRef<const Expr *> Args,
+ unsigned formatIdx, bool inFunctionCall,
+ Sema::VariadicCallType callType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg)
- : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
- FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
- HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
- usesPositionalArgs(false), atFirstArg(true),
- inFunctionCall(inFunctionCall), CallType(callType),
- CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
+ : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
+ FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
+ Beg(beg), HasVAListArg(hasVAListArg),
+ Args(Args), FormatIdx(formatIdx),
+ usesPositionalArgs(false), atFirstArg(true),
+ inFunctionCall(inFunctionCall), CallType(callType),
+ CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
CoveredArgs.resize(numDataArgs);
CoveredArgs.reset();
}
@@ -4744,18 +4745,22 @@
CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
const Expr *origFormatExpr,
const Sema::FormatStringType type, unsigned firstDataArg,
- unsigned numDataArgs, bool isObjC, const char *beg,
- bool hasVAListArg, ArrayRef<const Expr *> Args,
+ unsigned numDataArgs,
+ const char *beg, bool hasVAListArg,
+ ArrayRef<const Expr *> Args,
unsigned formatIdx, bool inFunctionCall,
Sema::VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg)
- : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
- numDataArgs, beg, hasVAListArg, Args, formatIdx,
- inFunctionCall, CallType, CheckedVarArgs,
- UncoveredArg) {}
+ : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
+ numDataArgs, beg, hasVAListArg, Args,
+ formatIdx, inFunctionCall, CallType, CheckedVarArgs,
+ UncoveredArg)
+ {}
- bool isObjCContext() const { return FSType == Sema::FST_NSString; }
+ bool isObjCContext() const {
+ return FSType == Sema::FST_NSString;
+ }
/// Returns true if '%@' specifiers are allowed in the format string.
bool allowsObjCArg() const {
@@ -5121,21 +5126,12 @@
}
// %P can only be used with os_log.
- if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
+ if (FSType != Sema::FST_OSLog &&
+ CS.getKind() == ConversionSpecifier::PArg) {
return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
specifierLen);
}
- // %n is not allowed with os_log.
- if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
- EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
- getLocationOfByte(CS.getStart()),
- /*IsStringLocation*/ false,
- getSpecifierRange(startSpecifier, specifierLen));
-
- return true;
- }
-
// Only scalars are allowed for os_trace.
if (FSType == Sema::FST_OSTrace &&
(CS.getKind() == ConversionSpecifier::PArg ||
@@ -5148,18 +5144,18 @@
// Check for use of public/private annotation outside of os_log().
if (FSType != Sema::FST_OSLog) {
if (FS.isPublic().isSet()) {
- EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
- << "public",
- getLocationOfByte(FS.isPublic().getPosition()),
- /*IsStringLocation*/ false,
- getSpecifierRange(startSpecifier, specifierLen));
+ EmitFormatDiagnostic(
+ S.PDiag(diag::warn_format_invalid_annotation) << "public",
+ getLocationOfByte(FS.isPublic().getPosition()),
+ /*IsStringLocation*/false,
+ getSpecifierRange(startSpecifier, specifierLen));
}
if (FS.isPrivate().isSet()) {
- EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
- << "private",
- getLocationOfByte(FS.isPrivate().getPosition()),
- /*IsStringLocation*/ false,
- getSpecifierRange(startSpecifier, specifierLen));
+ EmitFormatDiagnostic(
+ S.PDiag(diag::warn_format_invalid_annotation) << "private",
+ getLocationOfByte(FS.isPrivate().getPosition()),
+ /*IsStringLocation*/false,
+ getSpecifierRange(startSpecifier, specifierLen));
}
}
@@ -5178,10 +5174,10 @@
// Precision is mandatory for %P specifier.
if (CS.getKind() == ConversionSpecifier::PArg &&
FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
- EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
- getLocationOfByte(startSpecifier),
- /*IsStringLocation*/ false,
- getSpecifierRange(startSpecifier, specifierLen));
+ EmitFormatDiagnostic(
+ S.PDiag(diag::warn_format_P_no_precision),
+ getLocationOfByte(startSpecifier), /*IsStringLocation*/false,
+ getSpecifierRange(startSpecifier, specifierLen));
}
// Check each flag does not conflict with any other component.
@@ -5333,7 +5329,8 @@
using namespace analyze_printf;
// Now type check the data expression that matches the
// format specifier.
- const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
+ const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
+ isObjCContext());
if (!AT.isValid())
return true;
@@ -5429,8 +5426,8 @@
// We may be able to offer a FixItHint if it is a supported type.
PrintfSpecifier fixedFS = FS;
- bool success =
- fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
+ bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
+ S.Context, isObjCContext());
if (success) {
// Get the fix string from the fixed format specifier
@@ -5587,17 +5584,19 @@
public:
CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
const Expr *origFormatExpr, Sema::FormatStringType type,
- unsigned firstDataArg, unsigned numDataArgs,
- const char *beg, bool hasVAListArg,
- ArrayRef<const Expr *> Args, unsigned formatIdx,
- bool inFunctionCall, Sema::VariadicCallType CallType,
+ unsigned firstDataArg,
+ unsigned numDataArgs, const char *beg, bool hasVAListArg,
+ ArrayRef<const Expr *> Args,
+ unsigned formatIdx, bool inFunctionCall,
+ Sema::VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs,
UncoveredArgHandler &UncoveredArg)
- : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
- numDataArgs, beg, hasVAListArg, Args, formatIdx,
- inFunctionCall, CallType, CheckedVarArgs,
- UncoveredArg) {}
-
+ : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
+ numDataArgs, beg, hasVAListArg,
+ Args, formatIdx, inFunctionCall, CallType,
+ CheckedVarArgs, UncoveredArg)
+ {}
+
bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) override;
@@ -5809,11 +5808,10 @@
if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
Type == Sema::FST_OSTrace) {
- CheckPrintfHandler H(
- S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
- (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
- HasVAListArg, Args, format_idx, inFunctionCall, CallType,
- CheckedVarArgs, UncoveredArg);
+ CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
+ numDataArgs, Str, HasVAListArg, Args, format_idx,
+ inFunctionCall, CallType, CheckedVarArgs,
+ UncoveredArg);
if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
S.getLangOpts(),
@@ -5821,9 +5819,10 @@
Type == Sema::FST_FreeBSDKPrintf))
H.DoneProcessing();
} else if (Type == Sema::FST_Scanf) {
- CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
- numDataArgs, Str, HasVAListArg, Args, format_idx,
- inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
+ CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
+ Str, HasVAListArg, Args, format_idx,
+ inFunctionCall, CallType, CheckedVarArgs,
+ UncoveredArg);
if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
S.getLangOpts(),
diff --git a/lib/Sema/SemaDeclAttr.cpp b/lib/Sema/SemaDeclAttr.cpp
index 46c5844..3a9eb3e 100644
--- a/lib/Sema/SemaDeclAttr.cpp
+++ b/lib/Sema/SemaDeclAttr.cpp
@@ -2833,21 +2833,21 @@
/// types.
static FormatAttrKind getFormatAttrKind(StringRef Format) {
return llvm::StringSwitch<FormatAttrKind>(Format)
- // Check for formats that get handled specially.
- .Case("NSString", NSStringFormat)
- .Case("CFString", CFStringFormat)
- .Case("strftime", StrftimeFormat)
+ // Check for formats that get handled specially.
+ .Case("NSString", NSStringFormat)
+ .Case("CFString", CFStringFormat)
+ .Case("strftime", StrftimeFormat)
- // Otherwise, check for supported formats.
- .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
- .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
- .Case("kprintf", SupportedFormat) // OpenBSD.
- .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
- .Case("os_trace", SupportedFormat)
- .Case("os_log", SupportedFormat)
+ // Otherwise, check for supported formats.
+ .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
+ .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
+ .Case("kprintf", SupportedFormat) // OpenBSD.
+ .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
+ .Case("os_trace", SupportedFormat)
+ .Case("os_log", SupportedFormat)
- .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
- .Default(InvalidFormat);
+ .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
+ .Default(InvalidFormat);
}
/// Handle __attribute__((init_priority(priority))) attributes based on
diff --git a/test/CodeGen/builtins.c b/test/CodeGen/builtins.c
index 4be533d..2ce7113 100644
--- a/test/CodeGen/builtins.c
+++ b/test/CodeGen/builtins.c
@@ -353,7 +353,6 @@
// __builtin_longjmp isn't supported on all platforms, so only test it on X86.
#ifdef __x86_64__
-
// CHECK-LABEL: define void @test_builtin_longjmp
void test_builtin_longjmp(void **buffer) {
// CHECK: [[BITCAST:%.*]] = bitcast
@@ -361,7 +360,6 @@
__builtin_longjmp(buffer, 1);
// CHECK-NEXT: unreachable
}
-
#endif
// CHECK-LABEL: define i64 @test_builtin_readcyclecounter
@@ -372,7 +370,6 @@
// Behavior of __builtin_os_log differs between platforms, so only test on X86
#ifdef __x86_64__
-
// CHECK-LABEL: define void @test_builtin_os_log
// CHECK: (i8* [[BUF:%.*]], i32 [[I:%.*]], i8* [[DATA:%.*]])
void test_builtin_os_log(void *buf, int i, const char *data) {
@@ -428,98 +425,4 @@
__builtin_os_log_format(buf, "%d %{public}s %{private}.16P", i, data, data);
}
-// CHECK-LABEL: define void @test_builtin_os_log_errno
-// CHECK: (i8* [[BUF:%.*]], i8* [[DATA:%.*]])
-void test_builtin_os_log_errno(void *buf, const char *data) {
- volatile int len;
- // CHECK: store i8* [[BUF]], i8** [[BUF_ADDR:%.*]], align 8
- // CHECK: store i8* [[DATA]], i8** [[DATA_ADDR:%.*]], align 8
-
- // CHECK: store volatile i32 2
- len = __builtin_os_log_format_buffer_size("%S");
-
- // CHECK: [[BUF2:%.*]] = load i8*, i8** [[BUF_ADDR]]
- // CHECK: [[SUMMARY:%.*]] = getelementptr i8, i8* [[BUF2]], i64 0
- // CHECK: store i8 2, i8* [[SUMMARY]]
- // CHECK: [[NUM_ARGS:%.*]] = getelementptr i8, i8* [[BUF2]], i64 1
- // CHECK: store i8 1, i8* [[NUM_ARGS]]
-
- // CHECK: [[ARG1_DESC:%.*]] = getelementptr i8, i8* [[BUF2]], i64 2
- // CHECK: store i8 96, i8* [[ARG1_DESC]]
- // CHECK: [[ARG1_SIZE:%.*]] = getelementptr i8, i8* [[BUF2]], i64 3
- // CHECK: store i8 0, i8* [[ARG1_SIZE]]
- // CHECK: [[ARG1:%.*]] = getelementptr i8, i8* [[BUF2]], i64 4
- // CHECK: [[ARG1_INT:%.*]] = bitcast i8* [[ARG1]] to i32*
- // CHECK: store i32 0, i32* [[ARG1_INT]]
-
- __builtin_os_log_format(buf, "%m");
-}
-
-// CHECK-LABEL: define void @test_builtin_os_log_wide
-// CHECK: (i8* [[BUF:%.*]], i8* [[DATA:%.*]], i32* [[STR:%.*]])
-typedef int wchar_t;
-void test_builtin_os_log_wide(void *buf, const char *data, wchar_t *str) {
- volatile int len;
- // CHECK: store i8* [[BUF]], i8** [[BUF_ADDR:%.*]], align 8
- // CHECK: store i8* [[DATA]], i8** [[DATA_ADDR:%.*]], align 8
- // CHECK: store i32* [[STR]], i32** [[STR_ADDR:%.*]],
-
- // CHECK: store volatile i32 12
- len = __builtin_os_log_format_buffer_size("%S", str);
-
- // CHECK: [[BUF2:%.*]] = load i8*, i8** [[BUF_ADDR]]
- // CHECK: [[SUMMARY:%.*]] = getelementptr i8, i8* [[BUF2]], i64 0
- // CHECK: store i8 2, i8* [[SUMMARY]]
- // CHECK: [[NUM_ARGS:%.*]] = getelementptr i8, i8* [[BUF2]], i64 1
- // CHECK: store i8 1, i8* [[NUM_ARGS]]
-
- // CHECK: [[ARG1_DESC:%.*]] = getelementptr i8, i8* [[BUF2]], i64 2
- // CHECK: store i8 80, i8* [[ARG1_DESC]]
- // CHECK: [[ARG1_SIZE:%.*]] = getelementptr i8, i8* [[BUF2]], i64 3
- // CHECK: store i8 8, i8* [[ARG1_SIZE]]
- // CHECK: [[ARG1:%.*]] = getelementptr i8, i8* [[BUF2]], i64 4
- // CHECK: [[ARG1_PTR:%.*]] = bitcast i8* [[ARG1]] to i32**
- // CHECK: [[STR2:%.*]] = load i32*, i32** [[STR_ADDR]]
- // CHECK: store i32* [[STR2]], i32** [[ARG1_PTR]]
-
- __builtin_os_log_format(buf, "%S", str);
-}
-
-// CHECK-LABEL: define void @test_builtin_os_log_percent
-// CHECK: (i8* [[BUF:%.*]], i8* [[DATA1:%.*]], i8* [[DATA2:%.*]])
-// Check that the %% which does not consume any argument is correctly handled
-void test_builtin_os_log_percent(void *buf, const char *data1, const char *data2) {
- volatile int len;
- // CHECK: store i8* [[BUF]], i8** [[BUF_ADDR:%.*]], align 8
- // CHECK: store i8* [[DATA1]], i8** [[DATA1_ADDR:%.*]], align 8
- // CHECK: store i8* [[DATA2]], i8** [[DATA2_ADDR:%.*]], align 8
- // CHECK: store volatile i32 22
- len = __builtin_os_log_format_buffer_size("%s %% %s", data1, data2);
-
- // CHECK: [[BUF2:%.*]] = load i8*, i8** [[BUF_ADDR]]
- // CHECK: [[SUMMARY:%.*]] = getelementptr i8, i8* [[BUF2]], i64 0
- // CHECK: store i8 2, i8* [[SUMMARY]]
- // CHECK: [[NUM_ARGS:%.*]] = getelementptr i8, i8* [[BUF2]], i64 1
- // CHECK: store i8 2, i8* [[NUM_ARGS]]
- //
- // CHECK: [[ARG1_DESC:%.*]] = getelementptr i8, i8* [[BUF2]], i64 2
- // CHECK: store i8 32, i8* [[ARG1_DESC]]
- // CHECK: [[ARG1_SIZE:%.*]] = getelementptr i8, i8* [[BUF2]], i64 3
- // CHECK: store i8 8, i8* [[ARG1_SIZE]]
- // CHECK: [[ARG1:%.*]] = getelementptr i8, i8* [[BUF2]], i64 4
- // CHECK: [[ARG1_PTR:%.*]] = bitcast i8* [[ARG1]] to i8**
- // CHECK: [[DATA1:%.*]] = load i8*, i8** [[DATA1_ADDR]]
- // CHECK: store i8* [[DATA1]], i8** [[ARG1_PTR]]
- //
- // CHECK: [[ARG2_DESC:%.*]] = getelementptr i8, i8* [[BUF2]], i64 12
- // CHECK: store i8 32, i8* [[ARG2_DESC]]
- // CHECK: [[ARG2_SIZE:%.*]] = getelementptr i8, i8* [[BUF2]], i64 13
- // CHECK: store i8 8, i8* [[ARG2_SIZE]]
- // CHECK: [[ARG2:%.*]] = getelementptr i8, i8* [[BUF2]], i64 14
- // CHECK: [[ARG2_PTR:%.*]] = bitcast i8* [[ARG2]] to i8**
- // CHECK: [[DATA2:%.*]] = load i8*, i8** [[DATA2_ADDR]]
- // CHECK: store i8* [[DATA2]], i8** [[ARG2_PTR]]
- __builtin_os_log_format(buf, "%s %% %s", data1, data2);
-}
-
-#endif
\ No newline at end of file
+#endif
diff --git a/test/CodeGenObjC/os_log.m b/test/CodeGenObjC/os_log.m
index 5d48783..144d1cc 100644
--- a/test/CodeGenObjC/os_log.m
+++ b/test/CodeGenObjC/os_log.m
@@ -7,7 +7,7 @@
// rdar://problem/24528966
@class NSString;
-extern __attribute__((visibility("default"))) NSString *GenString();
+extern __attribute__((visibility("default"))) NSString * GenString();
// Behavior of __builtin_os_log differs between platforms, so only test on X86
#ifdef __x86_64__
diff --git a/test/SemaObjC/format-strings-oslog.m b/test/SemaObjC/format-strings-oslog.m
deleted file mode 100644
index 15c88e1..0000000
--- a/test/SemaObjC/format-strings-oslog.m
+++ /dev/null
@@ -1,65 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
-
-#include <stdarg.h>
-#include <stddef.h>
-#define __need_wint_t
-#include <stddef.h> // For wint_t and wchar_t
-
-int printf(const char *restrict, ...);
-
-@interface NSString
-@end
-
-void test_os_log_format(const char *pc, int i, void *p, void *buf) {
- __builtin_os_log_format(buf, "");
- __builtin_os_log_format(buf, "%d"); // expected-warning {{more '%' conversions than data arguments}}
- __builtin_os_log_format(buf, "%d", i);
- __builtin_os_log_format(buf, "%P", p); // expected-warning {{using '%P' format specifier without precision}}
- __builtin_os_log_format(buf, "%.10P", p);
- __builtin_os_log_format(buf, "%.*P", p); // expected-warning {{field precision should have type 'int', but argument has type 'void *'}}
- __builtin_os_log_format(buf, "%.*P", i, p);
- __builtin_os_log_format(buf, "%.*P", i, i); // expected-warning {{format specifies type 'void *' but the argument has type 'int'}}
- __builtin_os_log_format(buf, "%n"); // expected-error {{os_log() '%n' format specifier is not allowed}}
- __builtin_os_log_format(buf, pc); // expected-error {{os_log() format argument is not a string constant}}
-
- printf("%{private}s", pc); // expected-warning {{using 'private' format specifier annotation outside of os_log()/os_trace()}}
- __builtin_os_log_format(buf, "%{private}s", pc);
-
- // <rdar://problem/23835805>
- __builtin_os_log_format_buffer_size("no-args");
- __builtin_os_log_format(buf, "%s", "hi");
-
- // <rdar://problem/24828090>
- wchar_t wc = 'a';
- __builtin_os_log_format(buf, "%C", wc);
- printf("%C", wc);
- wchar_t wcs[] = {'a', 0};
- __builtin_os_log_format(buf, "%S", wcs);
- printf("%S", wcs);
-
- struct { char data[0x100]; } toobig;
- __builtin_os_log_format(buf, "%s", toobig); // expected-error {{os_log() argument 2 is too big (256 bytes, max 255)}}
-}
-
-// Test os_log_format primitive with ObjC string literal format argument.
-void test_objc(const char *pc, int i, void *p, void *buf, NSString *nss) {
- __builtin_os_log_format(buf, @"");
- __builtin_os_log_format(buf, @"%d"); // expected-warning {{more '%' conversions than data arguments}}
- __builtin_os_log_format(buf, @"%d", i);
- __builtin_os_log_format(buf, @"%P", p); // expected-warning {{using '%P' format specifier without precision}}
- __builtin_os_log_format(buf, @"%.10P", p);
- __builtin_os_log_format(buf, @"%.*P", p); // expected-warning {{field precision should have type 'int', but argument has type 'void *'}}
- __builtin_os_log_format(buf, @"%.*P", i, p);
- __builtin_os_log_format(buf, @"%.*P", i, i); // expected-warning {{format specifies type 'void *' but the argument has type 'int'}}
-
- __builtin_os_log_format(buf, @"%{private}s", pc);
- __builtin_os_log_format(buf, @"%@", nss);
-}
-
-// Test the os_log format attribute.
-void MyOSLog(const char *format, ...) __attribute__((format(os_log, 1, 2)));
-void test_attribute(void *p) {
- MyOSLog("%s\n", "Hello");
- MyOSLog("%d"); // expected-warning {{more '%' conversions than data arguments}}
- MyOSLog("%P", p); // expected-warning {{using '%P' format specifier without precision}}
-}