(Dcl)) {
Loc = FD->getLocation();
// Check for ObjC 'id' and class types that have been adorned with protocol
// information (id, C
*). The protocol references need to be rewritten!
const FunctionType *funcType = FD->getType()->getAs();
assert(funcType && "missing function type");
proto = dyn_cast(funcType);
if (!proto)
return;
Type = proto->getResultType();
}
else if (FieldDecl *FD = dyn_cast(Dcl)) {
Loc = FD->getLocation();
Type = FD->getType();
}
else
return;
if (needToScanForQualifiers(Type)) {
// Since types are unique, we need to scan the buffer.
const char *endBuf = SM->getCharacterData(Loc);
const char *startBuf = endBuf;
while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
startBuf--; // scan backward (from the decl location) for return type.
const char *startRef = 0, *endRef = 0;
if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
// Get the locations of the startRef, endRef.
SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
// Comment out the protocol references.
InsertText(LessLoc, "/*");
InsertText(GreaterLoc, "*/");
}
}
if (!proto)
return; // most likely, was a variable
// Now check arguments.
const char *startBuf = SM->getCharacterData(Loc);
const char *startFuncBuf = startBuf;
for (unsigned i = 0; i < proto->getNumArgs(); i++) {
if (needToScanForQualifiers(proto->getArgType(i))) {
// Since types are unique, we need to scan the buffer.
const char *endBuf = startBuf;
// scan forward (from the decl location) for argument types.
scanToNextArgument(endBuf);
const char *startRef = 0, *endRef = 0;
if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
// Get the locations of the startRef, endRef.
SourceLocation LessLoc =
Loc.getLocWithOffset(startRef-startFuncBuf);
SourceLocation GreaterLoc =
Loc.getLocWithOffset(endRef-startFuncBuf+1);
// Comment out the protocol references.
InsertText(LessLoc, "/*");
InsertText(GreaterLoc, "*/");
}
startBuf = ++endBuf;
}
else {
// If the function name is derived from a macro expansion, then the
// argument buffer will not follow the name. Need to speak with Chris.
while (*startBuf && *startBuf != ')' && *startBuf != ',')
startBuf++; // scan forward (from the decl location) for argument types.
startBuf++;
}
}
}
void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
QualType QT = ND->getType();
const Type* TypePtr = QT->getAs();
if (!isa(TypePtr))
return;
while (isa(TypePtr)) {
const TypeOfExprType *TypeOfExprTypePtr = cast(TypePtr);
QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
TypePtr = QT->getAs();
}
// FIXME. This will not work for multiple declarators; as in:
// __typeof__(a) b,c,d;
std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
const char *startBuf = SM->getCharacterData(DeclLoc);
if (ND->getInit()) {
std::string Name(ND->getNameAsString());
TypeAsString += " " + Name + " = ";
Expr *E = ND->getInit();
SourceLocation startLoc;
if (const CStyleCastExpr *ECE = dyn_cast(E))
startLoc = ECE->getLParenLoc();
else
startLoc = E->getLocStart();
startLoc = SM->getExpansionLoc(startLoc);
const char *endBuf = SM->getCharacterData(startLoc);
ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
}
else {
SourceLocation X = ND->getLocEnd();
X = SM->getExpansionLoc(X);
const char *endBuf = SM->getCharacterData(X);
ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
}
}
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
void RewriteObjC::SynthSelGetUidFunctionDecl() {
IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
SmallVector ArgTys;
ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
QualType getFuncType =
getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
SelGetUidIdent, getFuncType, 0,
SC_Extern,
SC_None, false);
}
void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
// declared in
if (FD->getIdentifier() &&
FD->getName() == "sel_registerName") {
SelGetUidFunctionDecl = FD;
return;
}
RewriteObjCQualifiedInterfaceTypes(FD);
}
void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
const char *argPtr = TypeString.c_str();
if (!strchr(argPtr, '^')) {
Str += TypeString;
return;
}
while (*argPtr) {
Str += (*argPtr == '^' ? '*' : *argPtr);
argPtr++;
}
}
// FIXME. Consolidate this routine with RewriteBlockPointerType.
void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
ValueDecl *VD) {
QualType Type = VD->getType();
std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
const char *argPtr = TypeString.c_str();
int paren = 0;
while (*argPtr) {
switch (*argPtr) {
case '(':
Str += *argPtr;
paren++;
break;
case ')':
Str += *argPtr;
paren--;
break;
case '^':
Str += '*';
if (paren == 1)
Str += VD->getNameAsString();
break;
default:
Str += *argPtr;
break;
}
argPtr++;
}
}
void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
const FunctionType *funcType = FD->getType()->getAs();
const FunctionProtoType *proto = dyn_cast(funcType);
if (!proto)
return;
QualType Type = proto->getResultType();
std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
FdStr += " ";
FdStr += FD->getName();
FdStr += "(";
unsigned numArgs = proto->getNumArgs();
for (unsigned i = 0; i < numArgs; i++) {
QualType ArgType = proto->getArgType(i);
RewriteBlockPointerType(FdStr, ArgType);
if (i+1 < numArgs)
FdStr += ", ";
}
FdStr += ");\n";
InsertText(FunLocStart, FdStr);
CurFunctionDeclToDeclareForBlock = 0;
}
// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
void RewriteObjC::SynthSuperContructorFunctionDecl() {
if (SuperContructorFunctionDecl)
return;
IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size());
SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, 0,
SC_Extern,
SC_None, false);
}
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
void RewriteObjC::SynthMsgSendFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size(),
true /*isVariadic*/);
MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, 0,
SC_Extern,
SC_None, false);
}
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
SmallVector ArgTys;
RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("objc_super"));
QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size(),
true /*isVariadic*/);
MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, 0,
SC_Extern,
SC_None, false);
}
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
void RewriteObjC::SynthMsgSendStretFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size(),
true /*isVariadic*/);
MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, 0,
SC_Extern,
SC_None, false);
}
// SynthMsgSendSuperStretFunctionDecl -
// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
IdentifierInfo *msgSendIdent =
&Context->Idents.get("objc_msgSendSuper_stret");
SmallVector ArgTys;
RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("objc_super"));
QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size(),
true /*isVariadic*/);
MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, 0,
SC_Extern,
SC_None, false);
}
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
SmallVector ArgTys;
QualType argT = Context->getObjCIdType();
assert(!argT.isNull() && "Can't find 'id' type");
ArgTys.push_back(argT);
argT = Context->getObjCSelType();
assert(!argT.isNull() && "Can't find 'SEL' type");
ArgTys.push_back(argT);
QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
&ArgTys[0], ArgTys.size(),
true /*isVariadic*/);
MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
msgSendIdent, msgSendType, 0,
SC_Extern,
SC_None, false);
}
// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
void RewriteObjC::SynthGetClassFunctionDecl() {
IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
SmallVector ArgTys;
ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size());
GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
getClassIdent, getClassType, 0,
SC_Extern,
SC_None, false);
}
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
void RewriteObjC::SynthGetSuperClassFunctionDecl() {
IdentifierInfo *getSuperClassIdent =
&Context->Idents.get("class_getSuperclass");
SmallVector ArgTys;
ArgTys.push_back(Context->getObjCClassType());
QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
&ArgTys[0], ArgTys.size());
GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
getSuperClassIdent,
getClassType, 0,
SC_Extern,
SC_None,
false);
}
// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
void RewriteObjC::SynthGetMetaClassFunctionDecl() {
IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
SmallVector ArgTys;
ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
&ArgTys[0], ArgTys.size());
GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
SourceLocation(),
SourceLocation(),
getClassIdent, getClassType, 0,
SC_Extern,
SC_None, false);
}
Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
QualType strType = getConstantStringStructType();
std::string S = "__NSConstantStringImpl_";
std::string tmpName = InFileName;
unsigned i;
for (i=0; i < tmpName.length(); i++) {
char c = tmpName.at(i);
// replace any non alphanumeric characters with '_'.
if (!isalpha(c) && (c < '0' || c > '9'))
tmpName[i] = '_';
}
S += tmpName;
S += "_";
S += utostr(NumObjCStringLiterals++);
Preamble += "static __NSConstantStringImpl " + S;
Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
Preamble += "0x000007c8,"; // utf8_str
// The pretty printer for StringLiteral handles escape characters properly.
std::string prettyBufS;
llvm::raw_string_ostream prettyBuf(prettyBufS);
Exp->getString()->printPretty(prettyBuf, *Context, 0,
PrintingPolicy(LangOpts));
Preamble += prettyBuf.str();
Preamble += ",";
Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
SourceLocation(), &Context->Idents.get(S),
strType, 0, SC_Static, SC_None);
DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
SourceLocation());
Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Context->getPointerType(DRE->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
// cast to NSConstantString *
CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
CK_CPointerToObjCPointerCast, Unop);
ReplaceStmt(Exp, cast);
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return cast;
}
// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
QualType RewriteObjC::getSuperStructType() {
if (!SuperStructDecl) {
SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("objc_super"));
QualType FieldTypes[2];
// struct objc_object *receiver;
FieldTypes[0] = Context->getObjCIdType();
// struct objc_class *super;
FieldTypes[1] = Context->getObjCClassType();
// Create fields
for (unsigned i = 0; i < 2; ++i) {
SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
SourceLocation(),
SourceLocation(), 0,
FieldTypes[i], 0,
/*BitWidth=*/0,
/*Mutable=*/false,
/*HasInit=*/false));
}
SuperStructDecl->completeDefinition();
}
return Context->getTagDeclType(SuperStructDecl);
}
QualType RewriteObjC::getConstantStringStructType() {
if (!ConstantStringDecl) {
ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("__NSConstantStringImpl"));
QualType FieldTypes[4];
// struct objc_object *receiver;
FieldTypes[0] = Context->getObjCIdType();
// int flags;
FieldTypes[1] = Context->IntTy;
// char *str;
FieldTypes[2] = Context->getPointerType(Context->CharTy);
// long length;
FieldTypes[3] = Context->LongTy;
// Create fields
for (unsigned i = 0; i < 4; ++i) {
ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
ConstantStringDecl,
SourceLocation(),
SourceLocation(), 0,
FieldTypes[i], 0,
/*BitWidth=*/0,
/*Mutable=*/true,
/*HasInit=*/false));
}
ConstantStringDecl->completeDefinition();
}
return Context->getTagDeclType(ConstantStringDecl);
}
Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
SourceLocation StartLoc,
SourceLocation EndLoc) {
if (!SelGetUidFunctionDecl)
SynthSelGetUidFunctionDecl();
if (!MsgSendFunctionDecl)
SynthMsgSendFunctionDecl();
if (!MsgSendSuperFunctionDecl)
SynthMsgSendSuperFunctionDecl();
if (!MsgSendStretFunctionDecl)
SynthMsgSendStretFunctionDecl();
if (!MsgSendSuperStretFunctionDecl)
SynthMsgSendSuperStretFunctionDecl();
if (!MsgSendFpretFunctionDecl)
SynthMsgSendFpretFunctionDecl();
if (!GetClassFunctionDecl)
SynthGetClassFunctionDecl();
if (!GetSuperClassFunctionDecl)
SynthGetSuperClassFunctionDecl();
if (!GetMetaClassFunctionDecl)
SynthGetMetaClassFunctionDecl();
// default to objc_msgSend().
FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
// May need to use objc_msgSend_stret() as well.
FunctionDecl *MsgSendStretFlavor = 0;
if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
QualType resultType = mDecl->getResultType();
if (resultType->isRecordType())
MsgSendStretFlavor = MsgSendStretFunctionDecl;
else if (resultType->isRealFloatingType())
MsgSendFlavor = MsgSendFpretFunctionDecl;
}
// Synthesize a call to objc_msgSend().
SmallVector MsgExprs;
switch (Exp->getReceiverKind()) {
case ObjCMessageExpr::SuperClass: {
MsgSendFlavor = MsgSendSuperFunctionDecl;
if (MsgSendStretFlavor)
MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
SmallVector InitExprs;
// set the receiver to self, the first argument to all methods.
InitExprs.push_back(
NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK_BitCast,
new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
false,
Context->getObjCIdType(),
VK_RValue,
SourceLocation()))
); // set the 'receiver'.
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
SmallVector ClsExprs;
QualType argType = Context->getPointerType(Context->CharTy);
ClsExprs.push_back(StringLiteral::Create(*Context,
ClassDecl->getIdentifier()->getName(),
StringLiteral::Ascii, false,
argType, SourceLocation()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc,
EndLoc);
// (Class)objc_getClass("CurrentClass")
CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
Context->getObjCClassType(),
CK_BitCast, Cls);
ClsExprs.clear();
ClsExprs.push_back(ArgExpr);
Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
&ClsExprs[0], ClsExprs.size(),
StartLoc, EndLoc);
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
// To turn off a warning, type-cast to 'id'
InitExprs.push_back( // set 'super class', using class_getSuperclass().
NoTypeInfoCStyleCastExpr(Context,
Context->getObjCIdType(),
CK_BitCast, Cls));
// struct objc_super
QualType superType = getSuperStructType();
Expr *SuperRep;
if (LangOpts.MicrosoftExt) {
SynthSuperContructorFunctionDecl();
// Simulate a contructor call...
DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
false, superType, VK_LValue,
SourceLocation());
SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
InitExprs.size(),
superType, VK_LValue,
SourceLocation());
// The code for super is a little tricky to prevent collision with
// the structure definition in the header. The rewriter has it's own
// internal definition (__rw_objc_super) that is uses. This is why
// we need the cast below. For example:
// (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
//
SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Context->getPointerType(SuperRep->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
SuperRep = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(superType),
CK_BitCast, SuperRep);
} else {
// (struct objc_super) { }
InitListExpr *ILE =
new (Context) InitListExpr(*Context, SourceLocation(),
&InitExprs[0], InitExprs.size(),
SourceLocation());
TypeSourceInfo *superTInfo
= Context->getTrivialTypeSourceInfo(superType);
SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
superType, VK_LValue,
ILE, false);
// struct objc_super *
SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Context->getPointerType(SuperRep->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
}
MsgExprs.push_back(SuperRep);
break;
}
case ObjCMessageExpr::Class: {
SmallVector ClsExprs;
QualType argType = Context->getPointerType(Context->CharTy);
ObjCInterfaceDecl *Class
= Exp->getClassReceiver()->getAs()->getInterface();
IdentifierInfo *clsName = Class->getIdentifier();
ClsExprs.push_back(StringLiteral::Create(*Context,
clsName->getName(),
StringLiteral::Ascii, false,
argType, SourceLocation()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
MsgExprs.push_back(Cls);
break;
}
case ObjCMessageExpr::SuperInstance:{
MsgSendFlavor = MsgSendSuperFunctionDecl;
if (MsgSendStretFlavor)
MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
SmallVector InitExprs;
InitExprs.push_back(
NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK_BitCast,
new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
false,
Context->getObjCIdType(),
VK_RValue, SourceLocation()))
); // set the 'receiver'.
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
SmallVector ClsExprs;
QualType argType = Context->getPointerType(Context->CharTy);
ClsExprs.push_back(StringLiteral::Create(*Context,
ClassDecl->getIdentifier()->getName(),
StringLiteral::Ascii, false, argType,
SourceLocation()));
CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
&ClsExprs[0],
ClsExprs.size(),
StartLoc, EndLoc);
// (Class)objc_getClass("CurrentClass")
CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
Context->getObjCClassType(),
CK_BitCast, Cls);
ClsExprs.clear();
ClsExprs.push_back(ArgExpr);
Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
&ClsExprs[0], ClsExprs.size(),
StartLoc, EndLoc);
// (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
// To turn off a warning, type-cast to 'id'
InitExprs.push_back(
// set 'super class', using class_getSuperclass().
NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK_BitCast, Cls));
// struct objc_super
QualType superType = getSuperStructType();
Expr *SuperRep;
if (LangOpts.MicrosoftExt) {
SynthSuperContructorFunctionDecl();
// Simulate a contructor call...
DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
false, superType, VK_LValue,
SourceLocation());
SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
InitExprs.size(),
superType, VK_LValue, SourceLocation());
// The code for super is a little tricky to prevent collision with
// the structure definition in the header. The rewriter has it's own
// internal definition (__rw_objc_super) that is uses. This is why
// we need the cast below. For example:
// (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
//
SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Context->getPointerType(SuperRep->getType()),
VK_RValue, OK_Ordinary,
SourceLocation());
SuperRep = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(superType),
CK_BitCast, SuperRep);
} else {
// (struct objc_super) { }
InitListExpr *ILE =
new (Context) InitListExpr(*Context, SourceLocation(),
&InitExprs[0], InitExprs.size(),
SourceLocation());
TypeSourceInfo *superTInfo
= Context->getTrivialTypeSourceInfo(superType);
SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
superType, VK_RValue, ILE,
false);
}
MsgExprs.push_back(SuperRep);
break;
}
case ObjCMessageExpr::Instance: {
// Remove all type-casts because it may contain objc-style types; e.g.
// Foo *.
Expr *recExpr = Exp->getInstanceReceiver();
while (CStyleCastExpr *CE = dyn_cast(recExpr))
recExpr = CE->getSubExpr();
CastKind CK = recExpr->getType()->isObjCObjectPointerType()
? CK_BitCast : recExpr->getType()->isBlockPointerType()
? CK_BlockPointerToObjCPointerCast
: CK_CPointerToObjCPointerCast;
recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK, recExpr);
MsgExprs.push_back(recExpr);
break;
}
}
// Create a call to sel_registerName("selName"), it will be the 2nd argument.
SmallVector SelExprs;
QualType argType = Context->getPointerType(Context->CharTy);
SelExprs.push_back(StringLiteral::Create(*Context,
Exp->getSelector().getAsString(),
StringLiteral::Ascii, false,
argType, SourceLocation()));
CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
&SelExprs[0], SelExprs.size(),
StartLoc,
EndLoc);
MsgExprs.push_back(SelExp);
// Now push any user supplied arguments.
for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Expr *userExpr = Exp->getArg(i);
// Make all implicit casts explicit...ICE comes in handy:-)
if (ImplicitCastExpr *ICE = dyn_cast(userExpr)) {
// Reuse the ICE type, it is exactly what the doctor ordered.
QualType type = ICE->getType();
if (needToScanForQualifiers(type))
type = Context->getObjCIdType();
// Make sure we convert "type (^)(...)" to "type (*)(...)".
(void)convertBlockPointerToFunctionPointer(type);
const Expr *SubExpr = ICE->IgnoreParenImpCasts();
CastKind CK;
if (SubExpr->getType()->isIntegralType(*Context) &&
type->isBooleanType()) {
CK = CK_IntegralToBoolean;
} else if (type->isObjCObjectPointerType()) {
if (SubExpr->getType()->isBlockPointerType()) {
CK = CK_BlockPointerToObjCPointerCast;
} else if (SubExpr->getType()->isPointerType()) {
CK = CK_CPointerToObjCPointerCast;
} else {
CK = CK_BitCast;
}
} else {
CK = CK_BitCast;
}
userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
}
// Make id cast into an 'id' cast.
else if (CStyleCastExpr *CE = dyn_cast(userExpr)) {
if (CE->getType()->isObjCQualifiedIdType()) {
while ((CE = dyn_cast(userExpr)))
userExpr = CE->getSubExpr();
CastKind CK;
if (userExpr->getType()->isIntegralType(*Context)) {
CK = CK_IntegralToPointer;
} else if (userExpr->getType()->isBlockPointerType()) {
CK = CK_BlockPointerToObjCPointerCast;
} else if (userExpr->getType()->isPointerType()) {
CK = CK_CPointerToObjCPointerCast;
} else {
CK = CK_BitCast;
}
userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
CK, userExpr);
}
}
MsgExprs.push_back(userExpr);
// We've transferred the ownership to MsgExprs. For now, we *don't* null
// out the argument in the original expression (since we aren't deleting
// the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
//Exp->setArg(i, 0);
}
// Generate the funky cast.
CastExpr *cast;
SmallVector ArgTypes;
QualType returnType;
// Push 'id' and 'SEL', the 2 implicit arguments.
if (MsgSendFlavor == MsgSendSuperFunctionDecl)
ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
else
ArgTypes.push_back(Context->getObjCIdType());
ArgTypes.push_back(Context->getObjCSelType());
if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
// Push any user argument types.
for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
E = OMD->param_end(); PI != E; ++PI) {
QualType t = (*PI)->getType()->isObjCQualifiedIdType()
? Context->getObjCIdType()
: (*PI)->getType();
// Make sure we convert "t (^)(...)" to "t (*)(...)".
(void)convertBlockPointerToFunctionPointer(t);
ArgTypes.push_back(t);
}
returnType = Exp->getType();
convertToUnqualifiedObjCType(returnType);
(void)convertBlockPointerToFunctionPointer(returnType);
} else {
returnType = Context->getObjCIdType();
}
// Get the type, we will need to reference it in a couple spots.
QualType msgSendType = MsgSendFlavor->getType();
// Create a reference to the objc_msgSend() declaration.
DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
VK_LValue, SourceLocation());
// Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
// If we don't do this cast, we get the following bizarre warning/note:
// xx.m:13: warning: function called through a non-compatible type
// xx.m:13: note: if this code is reached, the program will abort
cast = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(Context->VoidTy),
CK_BitCast, DRE);
// Now do the "normal" pointer to function cast.
QualType castType =
getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
// If we don't have a method decl, force a variadic cast.
Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
castType = Context->getPointerType(castType);
cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
cast);
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
const FunctionType *FT = msgSendType->getAs();
CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
MsgExprs.size(),
FT->getResultType(), VK_RValue,
EndLoc);
Stmt *ReplacingStmt = CE;
if (MsgSendStretFlavor) {
// We have the method which returns a struct/union. Must also generate
// call to objc_msgSend_stret and hang both varieties on a conditional
// expression which dictate which one to envoke depending on size of
// method's return type.
// Create a reference to the objc_msgSend_stret() declaration.
DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
false, msgSendType,
VK_LValue, SourceLocation());
// Need to cast objc_msgSend_stret to "void *" (see above comment).
cast = NoTypeInfoCStyleCastExpr(Context,
Context->getPointerType(Context->VoidTy),
CK_BitCast, STDRE);
// Now do the "normal" pointer to function cast.
castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
castType = Context->getPointerType(castType);
cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
cast);
// Don't forget the parens to enforce the proper binding.
PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
FT = msgSendType->getAs();
CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
MsgExprs.size(),
FT->getResultType(), VK_RValue,
SourceLocation());
// Build sizeof(returnType)
UnaryExprOrTypeTraitExpr *sizeofExpr =
new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
Context->getTrivialTypeSourceInfo(returnType),
Context->getSizeType(), SourceLocation(),
SourceLocation());
// (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
// FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
// For X86 it is more complicated and some kind of target specific routine
// is needed to decide what to do.
unsigned IntSize =
static_cast(Context->getTypeSize(Context->IntTy));
IntegerLiteral *limit = IntegerLiteral::Create(*Context,
llvm::APInt(IntSize, 8),
Context->IntTy,
SourceLocation());
BinaryOperator *lessThanExpr =
new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
VK_RValue, OK_Ordinary, SourceLocation());
// (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
ConditionalOperator *CondExpr =
new (Context) ConditionalOperator(lessThanExpr,
SourceLocation(), CE,
SourceLocation(), STCE,
returnType, VK_RValue, OK_Ordinary);
ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
CondExpr);
}
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return ReplacingStmt;
}
Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
Exp->getLocEnd());
// Now do the actual rewrite.
ReplaceStmt(Exp, ReplacingStmt);
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return ReplacingStmt;
}
// typedef struct objc_object Protocol;
QualType RewriteObjC::getProtocolType() {
if (!ProtocolTypeDecl) {
TypeSourceInfo *TInfo
= Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("Protocol"),
TInfo);
}
return Context->getTypeDeclType(ProtocolTypeDecl);
}
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
/// a synthesized/forward data reference (to the protocol's metadata).
/// The forward references (and metadata) are generated in
/// RewriteObjC::HandleTranslationUnit().
Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
IdentifierInfo *ID = &Context->Idents.get(Name);
VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
SourceLocation(), ID, getProtocolType(), 0,
SC_Extern, SC_None);
DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
VK_LValue, SourceLocation());
Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Context->getPointerType(DRE->getType()),
VK_RValue, OK_Ordinary, SourceLocation());
CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
CK_BitCast,
DerefExpr);
ReplaceStmt(Exp, castExpr);
ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
// delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
return castExpr;
}
bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
const char *endBuf) {
while (startBuf < endBuf) {
if (*startBuf == '#') {
// Skip whitespace.
for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
;
if (!strncmp(startBuf, "if", strlen("if")) ||
!strncmp(startBuf, "ifdef", strlen("ifdef")) ||
!strncmp(startBuf, "ifndef", strlen("ifndef")) ||
!strncmp(startBuf, "define", strlen("define")) ||
!strncmp(startBuf, "undef", strlen("undef")) ||
!strncmp(startBuf, "else", strlen("else")) ||
!strncmp(startBuf, "elif", strlen("elif")) ||
!strncmp(startBuf, "endif", strlen("endif")) ||
!strncmp(startBuf, "pragma", strlen("pragma")) ||
!strncmp(startBuf, "include", strlen("include")) ||
!strncmp(startBuf, "import", strlen("import")) ||
!strncmp(startBuf, "include_next", strlen("include_next")))
return true;
}
startBuf++;
}
return false;
}
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
/// an objective-c class with ivars.
void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
std::string &Result) {
assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
assert(CDecl->getName() != "" &&
"Name missing in SynthesizeObjCInternalStruct");
// Do not synthesize more than once.
if (ObjCSynthesizedStructs.count(CDecl))
return;
ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
int NumIvars = CDecl->ivar_size();
SourceLocation LocStart = CDecl->getLocStart();
SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
const char *startBuf = SM->getCharacterData(LocStart);
const char *endBuf = SM->getCharacterData(LocEnd);
// If no ivars and no root or if its root, directly or indirectly,
// have no ivars (thus not synthesized) then no need to synthesize this class.
if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
(!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
ReplaceText(LocStart, endBuf-startBuf, Result);
return;
}
// FIXME: This has potential of causing problem. If
// SynthesizeObjCInternalStruct is ever called recursively.
Result += "\nstruct ";
Result += CDecl->getNameAsString();
if (LangOpts.MicrosoftExt)
Result += "_IMPL";
if (NumIvars > 0) {
const char *cursor = strchr(startBuf, '{');
assert((cursor && endBuf)
&& "SynthesizeObjCInternalStruct - malformed @interface");
// If the buffer contains preprocessor directives, we do more fine-grained
// rewrites. This is intended to fix code that looks like (which occurs in
// NSURL.h, for example):
//
// #ifdef XYZ
// @interface Foo : NSObject
// #else
// @interface FooBar : NSObject
// #endif
// {
// int i;
// }
// @end
//
// This clause is segregated to avoid breaking the common case.
if (BufferContainsPPDirectives(startBuf, cursor)) {
SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
CDecl->getAtStartLoc();
const char *endHeader = SM->getCharacterData(L);
endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
if (CDecl->protocol_begin() != CDecl->protocol_end()) {
// advance to the end of the referenced protocols.
while (endHeader < cursor && *endHeader != '>') endHeader++;
endHeader++;
}
// rewrite the original header
ReplaceText(LocStart, endHeader-startBuf, Result);
} else {
// rewrite the original header *without* disturbing the '{'
ReplaceText(LocStart, cursor-startBuf, Result);
}
if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Result = "\n struct ";
Result += RCDecl->getNameAsString();
Result += "_IMPL ";
Result += RCDecl->getNameAsString();
Result += "_IVARS;\n";
// insert the super class structure definition.
SourceLocation OnePastCurly =
LocStart.getLocWithOffset(cursor-startBuf+1);
InsertText(OnePastCurly, Result);
}
cursor++; // past '{'
// Now comment out any visibility specifiers.
while (cursor < endBuf) {
if (*cursor == '@') {
SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
// Skip whitespace.
for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
/*scan*/;
// FIXME: presence of @public, etc. inside comment results in
// this transformation as well, which is still correct c-code.
if (!strncmp(cursor, "public", strlen("public")) ||
!strncmp(cursor, "private", strlen("private")) ||
!strncmp(cursor, "package", strlen("package")) ||
!strncmp(cursor, "protected", strlen("protected")))
InsertText(atLoc, "// ");
}
// FIXME: If there are cases where '<' is used in ivar declaration part
// of user code, then scan the ivar list and use needToScanForQualifiers
// for type checking.
else if (*cursor == '<') {
SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
InsertText(atLoc, "/* ");
cursor = strchr(cursor, '>');
cursor++;
atLoc = LocStart.getLocWithOffset(cursor-startBuf);
InsertText(atLoc, " */");
} else if (*cursor == '^') { // rewrite block specifier.
SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
ReplaceText(caretLoc, 1, "*");
}
cursor++;
}
// Don't forget to add a ';'!!
InsertText(LocEnd.getLocWithOffset(1), ";");
} else { // we don't have any instance variables - insert super struct.
endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Result += " {\n struct ";
Result += RCDecl->getNameAsString();
Result += "_IMPL ";
Result += RCDecl->getNameAsString();
Result += "_IVARS;\n};\n";
ReplaceText(LocStart, endBuf-startBuf, Result);
}
// Mark this struct as having been generated.
if (!ObjCSynthesizedStructs.insert(CDecl))
llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
}
//===----------------------------------------------------------------------===//
// Meta Data Emission
//===----------------------------------------------------------------------===//
/// RewriteImplementations - This routine rewrites all method implementations
/// and emits meta-data.
void RewriteObjC::RewriteImplementations() {
int ClsDefCount = ClassImplementation.size();
int CatDefCount = CategoryImplementation.size();
// Rewrite implemented methods
for (int i = 0; i < ClsDefCount; i++)
RewriteImplementationDecl(ClassImplementation[i]);
for (int i = 0; i < CatDefCount; i++)
RewriteImplementationDecl(CategoryImplementation[i]);
}
void RewriteObjC::RewriteByRefString(std::string &ResultStr,
const std::string &Name,
ValueDecl *VD, bool def) {
assert(BlockByRefDeclNo.count(VD) &&
"RewriteByRefString: ByRef decl missing");
if (def)
ResultStr += "struct ";
ResultStr += "__Block_byref_" + Name +
"_" + utostr(BlockByRefDeclNo[VD]) ;
}
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
if (VarDecl *Var = dyn_cast(VD))
return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
return false;
}
std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
StringRef funcName,
std::string Tag) {
const FunctionType *AFT = CE->getFunctionType();
QualType RT = AFT->getResultType();
std::string StructRef = "struct " + Tag;
std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
funcName.str() + "_" + "block_func_" + utostr(i);
BlockDecl *BD = CE->getBlockDecl();
if (isa(AFT)) {
// No user-supplied arguments. Still need to pass in a pointer to the
// block (to reference imported block decl refs).
S += "(" + StructRef + " *__cself)";
} else if (BD->param_empty()) {
S += "(" + StructRef + " *__cself)";
} else {
const FunctionProtoType *FT = cast(AFT);
assert(FT && "SynthesizeBlockFunc: No function proto");
S += '(';
// first add the implicit argument.
S += StructRef + " *__cself, ";
std::string ParamStr;
for (BlockDecl::param_iterator AI = BD->param_begin(),
E = BD->param_end(); AI != E; ++AI) {
if (AI != BD->param_begin()) S += ", ";
ParamStr = (*AI)->getNameAsString();
QualType QT = (*AI)->getType();
(void)convertBlockPointerToFunctionPointer(QT);
QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
S += ParamStr;
}
if (FT->isVariadic()) {
if (!BD->param_empty()) S += ", ";
S += "...";
}
S += ')';
}
S += " {\n";
// Create local declarations to avoid rewriting all closure decl ref exprs.
// First, emit a declaration for all "by ref" decls.
for (SmallVector::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
S += " ";
std::string Name = (*I)->getNameAsString();
std::string TypeString;
RewriteByRefString(TypeString, Name, (*I));
TypeString += " *";
Name = TypeString + Name;
S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
}
// Next, emit a declaration for all "by copy" declarations.
for (SmallVector::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
S += " ";
// Handle nested closure invocation. For example:
//
// void (^myImportedClosure)(void);
// myImportedClosure = ^(void) { setGlobalInt(x + y); };
//
// void (^anotherClosure)(void);
// anotherClosure = ^(void) {
// myImportedClosure(); // import and invoke the closure
// };
//
if (isTopLevelBlockPointerType((*I)->getType())) {
RewriteBlockPointerTypeVariable(S, (*I));
S += " = (";
RewriteBlockPointerType(S, (*I)->getType());
S += ")";
S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
}
else {
std::string Name = (*I)->getNameAsString();
QualType QT = (*I)->getType();
if (HasLocalVariableExternalStorage(*I))
QT = Context->getPointerType(QT);
QT.getAsStringInternal(Name, Context->getPrintingPolicy());
S += Name + " = __cself->" +
(*I)->getNameAsString() + "; // bound by copy\n";
}
}
std::string RewrittenStr = RewrittenBlockExprs[CE];
const char *cstr = RewrittenStr.c_str();
while (*cstr++ != '{') ;
S += cstr;
S += "\n";
return S;
}
std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
StringRef funcName,
std::string Tag) {
std::string StructRef = "struct " + Tag;
std::string S = "static void __";
S += funcName;
S += "_block_copy_" + utostr(i);
S += "(" + StructRef;
S += "*dst, " + StructRef;
S += "*src) {";
for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(),
E = ImportedBlockDecls.end(); I != E; ++I) {
ValueDecl *VD = (*I);
S += "_Block_object_assign((void*)&dst->";
S += (*I)->getNameAsString();
S += ", (void*)src->";
S += (*I)->getNameAsString();
if (BlockByRefDeclsPtrSet.count((*I)))
S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
else if (VD->getType()->isBlockPointerType())
S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
else
S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
}
S += "}\n";
S += "\nstatic void __";
S += funcName;
S += "_block_dispose_" + utostr(i);
S += "(" + StructRef;
S += "*src) {";
for (llvm::SmallPtrSet::iterator I = ImportedBlockDecls.begin(),
E = ImportedBlockDecls.end(); I != E; ++I) {
ValueDecl *VD = (*I);
S += "_Block_object_dispose((void*)src->";
S += (*I)->getNameAsString();
if (BlockByRefDeclsPtrSet.count((*I)))
S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
else if (VD->getType()->isBlockPointerType())
S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
else
S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
}
S += "}\n";
return S;
}
std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
std::string Desc) {
std::string S = "\nstruct " + Tag;
std::string Constructor = " " + Tag;
S += " {\n struct __block_impl impl;\n";
S += " struct " + Desc;
S += "* Desc;\n";
Constructor += "(void *fp, "; // Invoke function pointer.
Constructor += "struct " + Desc; // Descriptor pointer.
Constructor += " *desc";
if (BlockDeclRefs.size()) {
// Output all "by copy" declarations.
for (SmallVector::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
S += " ";
std::string FieldName = (*I)->getNameAsString();
std::string ArgName = "_" + FieldName;
// Handle nested closure invocation. For example:
//
// void (^myImportedBlock)(void);
// myImportedBlock = ^(void) { setGlobalInt(x + y); };
//
// void (^anotherBlock)(void);
// anotherBlock = ^(void) {
// myImportedBlock(); // import and invoke the closure
// };
//
if (isTopLevelBlockPointerType((*I)->getType())) {
S += "struct __block_impl *";
Constructor += ", void *" + ArgName;
} else {
QualType QT = (*I)->getType();
if (HasLocalVariableExternalStorage(*I))
QT = Context->getPointerType(QT);
QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Constructor += ", " + ArgName;
}
S += FieldName + ";\n";
}
// Output all "by ref" declarations.
for (SmallVector::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
S += " ";
std::string FieldName = (*I)->getNameAsString();
std::string ArgName = "_" + FieldName;
{
std::string TypeString;
RewriteByRefString(TypeString, FieldName, (*I));
TypeString += " *";
FieldName = TypeString + FieldName;
ArgName = TypeString + ArgName;
Constructor += ", " + ArgName;
}
S += FieldName + "; // by ref\n";
}
// Finish writing the constructor.
Constructor += ", int flags=0)";
// Initialize all "by copy" arguments.
bool firsTime = true;
for (SmallVector::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
std::string Name = (*I)->getNameAsString();
if (firsTime) {
Constructor += " : ";
firsTime = false;
}
else
Constructor += ", ";
if (isTopLevelBlockPointerType((*I)->getType()))
Constructor += Name + "((struct __block_impl *)_" + Name + ")";
else
Constructor += Name + "(_" + Name + ")";
}
// Initialize all "by ref" arguments.
for (SmallVector::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
std::string Name = (*I)->getNameAsString();
if (firsTime) {
Constructor += " : ";
firsTime = false;
}
else
Constructor += ", ";
Constructor += Name + "(_" + Name + "->__forwarding)";
}
Constructor += " {\n";
if (GlobalVarDecl)
Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
else
Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Constructor += " Desc = desc;\n";
} else {
// Finish writing the constructor.
Constructor += ", int flags=0) {\n";
if (GlobalVarDecl)
Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
else
Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Constructor += " Desc = desc;\n";
}
Constructor += " ";
Constructor += "}\n";
S += Constructor;
S += "};\n";
return S;
}
std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
std::string ImplTag, int i,
StringRef FunName,
unsigned hasCopy) {
std::string S = "\nstatic struct " + DescTag;
S += " {\n unsigned long reserved;\n";
S += " unsigned long Block_size;\n";
if (hasCopy) {
S += " void (*copy)(struct ";
S += ImplTag; S += "*, struct ";
S += ImplTag; S += "*);\n";
S += " void (*dispose)(struct ";
S += ImplTag; S += "*);\n";
}
S += "} ";
S += DescTag + "_DATA = { 0, sizeof(struct ";
S += ImplTag + ")";
if (hasCopy) {
S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
}
S += "};\n";
return S;
}
void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
StringRef FunName) {
// Insert declaration for the function in which block literal is used.
if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
bool RewriteSC = (GlobalVarDecl &&
!Blocks.empty() &&
GlobalVarDecl->getStorageClass() == SC_Static &&
GlobalVarDecl->getType().getCVRQualifiers());
if (RewriteSC) {
std::string SC(" void __");
SC += GlobalVarDecl->getNameAsString();
SC += "() {}";
InsertText(FunLocStart, SC);
}
// Insert closures that were part of the function.
for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
CollectBlockDeclRefInfo(Blocks[i]);
// Need to copy-in the inner copied-in variables not actually used in this
// block.
for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
DeclRefExpr *Exp = InnerDeclRefs[count++];
ValueDecl *VD = Exp->getDecl();
BlockDeclRefs.push_back(Exp);
if (!VD->hasAttr() && !BlockByCopyDeclsPtrSet.count(VD)) {
BlockByCopyDeclsPtrSet.insert(VD);
BlockByCopyDecls.push_back(VD);
}
if (VD->hasAttr() && !BlockByRefDeclsPtrSet.count(VD)) {
BlockByRefDeclsPtrSet.insert(VD);
BlockByRefDecls.push_back(VD);
}
// imported objects in the inner blocks not used in the outer
// blocks must be copied/disposed in the outer block as well.
if (VD->hasAttr() ||
VD->getType()->isObjCObjectPointerType() ||
VD->getType()->isBlockPointerType())
ImportedBlockDecls.insert(VD);
}
std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
InsertText(FunLocStart, CI);
std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
InsertText(FunLocStart, CF);
if (ImportedBlockDecls.size()) {
std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
InsertText(FunLocStart, HF);
}
std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
ImportedBlockDecls.size() > 0);
InsertText(FunLocStart, BD);
BlockDeclRefs.clear();
BlockByRefDecls.clear();
BlockByRefDeclsPtrSet.clear();
BlockByCopyDecls.clear();
BlockByCopyDeclsPtrSet.clear();
ImportedBlockDecls.clear();
}
if (RewriteSC) {
// Must insert any 'const/volatile/static here. Since it has been
// removed as result of rewriting of block literals.
std::string SC;
if (GlobalVarDecl->getStorageClass() == SC_Static)
SC = "static ";
if (GlobalVarDecl->getType().isConstQualified())
SC += "const ";
if (GlobalVarDecl->getType().isVolatileQualified())
SC += "volatile ";
if (GlobalVarDecl->getType().isRestrictQualified())
SC += "restrict ";
InsertText(FunLocStart, SC);
}
Blocks.clear();
InnerDeclRefsCount.clear();
InnerDeclRefs.clear();
RewrittenBlockExprs.clear();
}
void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
StringRef FuncName = FD->getName();
SynthesizeBlockLiterals(FunLocStart, FuncName);
}
static void BuildUniqueMethodName(std::string &Name,
ObjCMethodDecl *MD) {
ObjCInterfaceDecl *IFace = MD->getClassInterface();
Name = IFace->getName();
Name += "__" + MD->getSelector().getAsString();
// Convert colons to underscores.
std::string::size_type loc = 0;
while ((loc = Name.find(":", loc)) != std::string::npos)
Name.replace(loc, 1, "_");
}
void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
//fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
//SourceLocation FunLocStart = MD->getLocStart();
SourceLocation FunLocStart = MD->getLocStart();
std::string FuncName;
BuildUniqueMethodName(FuncName, MD);
SynthesizeBlockLiterals(FunLocStart, FuncName);
}
void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
for (Stmt::child_range CI = S->children(); CI; ++CI)
if (*CI) {
if (BlockExpr *CBE = dyn_cast(*CI))
GetBlockDeclRefExprs(CBE->getBody());
else
GetBlockDeclRefExprs(*CI);
}
// Handle specific things.
if (DeclRefExpr *DRE = dyn_cast(S)) {
if (DRE->refersToEnclosingLocal()) {
// FIXME: Handle enums.
if (!isa(DRE->getDecl()))
BlockDeclRefs.push_back(DRE);
if (HasLocalVariableExternalStorage(DRE->getDecl()))
BlockDeclRefs.push_back(DRE);
}
}
return;
}
void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
SmallVector &InnerBlockDeclRefs,
llvm::SmallPtrSet &InnerContexts) {
for (Stmt::child_range CI = S->children(); CI; ++CI)
if (*CI) {
if (BlockExpr *CBE = dyn_cast(*CI)) {
InnerContexts.insert(cast(CBE->getBlockDecl()));
GetInnerBlockDeclRefExprs(CBE->getBody(),
InnerBlockDeclRefs,
InnerContexts);
}
else
GetInnerBlockDeclRefExprs(*CI,
InnerBlockDeclRefs,
InnerContexts);
}
// Handle specific things.
if (DeclRefExpr *DRE = dyn_cast(S)) {
if (DRE->refersToEnclosingLocal()) {
if (!isa(DRE->getDecl()) &&
!InnerContexts.count(DRE->getDecl()->getDeclContext()))
InnerBlockDeclRefs.push_back(DRE);
if (VarDecl *Var = dyn_cast(DRE->getDecl()))
if (Var->isFunctionOrMethodVarDecl())
ImportedLocalExternalDecls.insert(Var);
}
}
return;
}
/// convertFunctionTypeOfBlocks - This routine converts a function type
/// whose result type may be a block pointer or whose argument type(s)
/// might be block pointers to an equivalent function type replacing
/// all block pointers to function pointers.
QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
const FunctionProtoType *FTP = dyn_cast(FT);
// FTP will be null for closures that don't take arguments.
// Generate a funky cast.
SmallVector ArgTypes;
QualType Res = FT->getResultType();
bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
if (FTP) {
for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
E = FTP->arg_type_end(); I && (I != E); ++I) {
QualType t = *I;
// Make sure we convert "t (^)(...)" to "t (*)(...)".
if (convertBlockPointerToFunctionPointer(t))
HasBlockType = true;
ArgTypes.push_back(t);
}
}
QualType FuncType;
// FIXME. Does this work if block takes no argument but has a return type
// which is of block type?
if (HasBlockType)
FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
else FuncType = QualType(FT, 0);
return FuncType;
}
Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
// Navigate to relevant type information.
const BlockPointerType *CPT = 0;
if (const DeclRefExpr *DRE = dyn_cast(BlockExp)) {
CPT = DRE->getType()->getAs();
} else if (const MemberExpr *MExpr = dyn_cast(BlockExp)) {
CPT = MExpr->getType()->getAs();
}
else if (const ParenExpr *PRE = dyn_cast(BlockExp)) {
return SynthesizeBlockCall(Exp, PRE->getSubExpr());
}
else if (const ImplicitCastExpr *IEXPR = dyn_cast(BlockExp))
CPT = IEXPR->getType()->getAs();
else if (const ConditionalOperator *CEXPR =
dyn_cast(BlockExp)) {
Expr *LHSExp = CEXPR->getLHS();
Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
Expr *RHSExp = CEXPR->getRHS();
Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
Expr *CONDExp = CEXPR->getCond();
ConditionalOperator *CondExpr =
new (Context) ConditionalOperator(CONDExp,
SourceLocation(), cast(LHSStmt),
SourceLocation(), cast(RHSStmt),
Exp->getType(), VK_RValue, OK_Ordinary);
return CondExpr;
} else if (const ObjCIvarRefExpr *IRE = dyn_cast(BlockExp)) {
CPT = IRE->getType()->getAs();
} else if (const PseudoObjectExpr *POE
= dyn_cast(BlockExp)) {
CPT = POE->getType()->castAs();
} else {
assert(1 && "RewriteBlockClass: Bad type");
}
assert(CPT && "RewriteBlockClass: Bad type");
const FunctionType *FT = CPT->getPointeeType()->getAs();
assert(FT && "RewriteBlockClass: Bad type");
const FunctionProtoType *FTP = dyn_cast(FT);
// FTP will be null for closures that don't take arguments.
RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get("__block_impl"));
QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
// Generate a funky cast.
SmallVector ArgTypes;
// Push the block argument type.
ArgTypes.push_back(PtrBlock);
if (FTP) {
for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
E = FTP->arg_type_end(); I && (I != E); ++I) {
QualType t = *I;
// Make sure we convert "t (^)(...)" to "t (*)(...)".
if (!convertBlockPointerToFunctionPointer(t))
convertToUnqualifiedObjCType(t);
ArgTypes.push_back(t);
}
}
// Now do the pointer to function cast.
QualType PtrToFuncCastType
= getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
CK_BitCast,
const_cast(BlockExp));
// Don't forget the parens to enforce the proper binding.
ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
BlkCast);
//PE->dump();
FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
SourceLocation(),
&Context->Idents.get("FuncPtr"),
Context->VoidPtrTy, 0,
/*BitWidth=*/0, /*Mutable=*/true,
/*HasInit=*/false);
MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
FD->getType(), VK_LValue,
OK_Ordinary);
CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
CK_BitCast, ME);
PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
SmallVector BlkExprs;
// Add the implicit argument.
BlkExprs.push_back(BlkCast);
// Add the user arguments.
for (CallExpr::arg_iterator I = Exp->arg_begin(),
E = Exp->arg_end(); I != E; ++I) {
BlkExprs.push_back(*I);
}
CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
BlkExprs.size(),
Exp->getType(), VK_RValue,
SourceLocation());
return CE;
}
// We need to return the rewritten expression to handle cases where the
// BlockDeclRefExpr is embedded in another expression being rewritten.
// For example:
//
// int main() {
// __block Foo *f;
// __block int i;
//
// void (^myblock)() = ^() {
// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
// i = 77;
// };
//}
Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
// Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
// for each DeclRefExp where BYREFVAR is name of the variable.
ValueDecl *VD = DeclRefExp->getDecl();
bool isArrow = DeclRefExp->refersToEnclosingLocal();
FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
SourceLocation(),
&Context->Idents.get("__forwarding"),
Context->VoidPtrTy, 0,
/*BitWidth=*/0, /*Mutable=*/true,
/*HasInit=*/false);
MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
FD, SourceLocation(),
FD->getType(), VK_LValue,
OK_Ordinary);
StringRef Name = VD->getName();
FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
&Context->Idents.get(Name),
Context->VoidPtrTy, 0,
/*BitWidth=*/0, /*Mutable=*/true,
/*HasInit=*/false);
ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
DeclRefExp->getType(), VK_LValue, OK_Ordinary);
// Need parens to enforce precedence.
ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
DeclRefExp->getExprLoc(),
ME);
ReplaceStmt(DeclRefExp, PE);
return PE;
}
// Rewrites the imported local variable V with external storage
// (static, extern, etc.) as *V
//
Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
ValueDecl *VD = DRE->getDecl();
if (VarDecl *Var = dyn_cast(VD))
if (!ImportedLocalExternalDecls.count(Var))
return DRE;
Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
VK_LValue, OK_Ordinary,
DRE->getLocation());
// Need parens to enforce precedence.
ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
Exp);
ReplaceStmt(DRE, PE);
return PE;
}
void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
SourceLocation LocStart = CE->getLParenLoc();
SourceLocation LocEnd = CE->getRParenLoc();
// Need to avoid trying to rewrite synthesized casts.
if (LocStart.isInvalid())
return;
// Need to avoid trying to rewrite casts contained in macros.
if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
return;
const char *startBuf = SM->getCharacterData(LocStart);
const char *endBuf = SM->getCharacterData(LocEnd);
QualType QT = CE->getType();
const Type* TypePtr = QT->getAs();
if (isa(TypePtr)) {
const TypeOfExprType *TypeOfExprTypePtr = cast(TypePtr);
QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
std::string TypeAsString = "(";
RewriteBlockPointerType(TypeAsString, QT);
TypeAsString += ")";
ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
return;
}
// advance the location to startArgList.
const char *argPtr = startBuf;
while (*argPtr++ && (argPtr < endBuf)) {
switch (*argPtr) {
case '^':
// Replace the '^' with '*'.
LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
ReplaceText(LocStart, 1, "*");
break;
}
}
return;
}
void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
SourceLocation DeclLoc = FD->getLocation();
unsigned parenCount = 0;
// We have 1 or more arguments that have closure pointers.
const char *startBuf = SM->getCharacterData(DeclLoc);
const char *startArgList = strchr(startBuf, '(');
assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
parenCount++;
// advance the location to startArgList.
DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
assert((DeclLoc.isValid()) && "Invalid DeclLoc");
const char *argPtr = startArgList;
while (*argPtr++ && parenCount) {
switch (*argPtr) {
case '^':
// Replace the '^' with '*'.
DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
ReplaceText(DeclLoc, 1, "*");
break;
case '(':
parenCount++;
break;
case ')':
parenCount--;
break;
}
}
return;
}
bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
const FunctionProtoType *FTP;
const PointerType *PT = QT->getAs();
if (PT) {
FTP = PT->getPointeeType()->getAs();
} else {
const BlockPointerType *BPT = QT->getAs();
assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
FTP = BPT->getPointeeType()->getAs();
}
if (FTP) {
for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
E = FTP->arg_type_end(); I != E; ++I)
if (isTopLevelBlockPointerType(*I))
return true;
}
return false;
}
bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
const FunctionProtoType *FTP;
const PointerType *PT = QT->getAs();
if (PT) {
FTP = PT->getPointeeType()->getAs();
} else {
const BlockPointerType *BPT = QT->getAs();
assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
FTP = BPT->getPointeeType()->getAs();
}
if (FTP) {
for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
E = FTP->arg_type_end(); I != E; ++I) {
if ((*I)->isObjCQualifiedIdType())
return true;
if ((*I)->isObjCObjectPointerType() &&
(*I)->getPointeeType()->isObjCQualifiedInterfaceType())
return true;
}
}
return false;
}
void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
const char *&RParen) {
const char *argPtr = strchr(Name, '(');
assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
LParen = argPtr; // output the start.
argPtr++; // skip past the left paren.
unsigned parenCount = 1;
while (*argPtr && parenCount) {
switch (*argPtr) {
case '(': parenCount++; break;
case ')': parenCount--; break;
default: break;
}
if (parenCount) argPtr++;
}
assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
RParen = argPtr; // output the end
}
void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
if (FunctionDecl *FD = dyn_cast(ND)) {
RewriteBlockPointerFunctionArgs(FD);
return;
}
// Handle Variables and Typedefs.
SourceLocation DeclLoc = ND->getLocation();
QualType DeclT;
if (VarDecl *VD = dyn_cast(ND))
DeclT = VD->getType();
else if (TypedefNameDecl *TDD = dyn_cast(ND))
DeclT = TDD->getUnderlyingType();
else if (FieldDecl *FD = dyn_cast(ND))
DeclT = FD->getType();
else
llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
const char *startBuf = SM->getCharacterData(DeclLoc);
const char *endBuf = startBuf;
// scan backward (from the decl location) for the end of the previous decl.
while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
startBuf--;
SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
std::string buf;
unsigned OrigLength=0;
// *startBuf != '^' if we are dealing with a pointer to function that
// may take block argument types (which will be handled below).
if (*startBuf == '^') {
// Replace the '^' with '*', computing a negative offset.
buf = '*';
startBuf++;
OrigLength++;
}
while (*startBuf != ')') {
buf += *startBuf;
startBuf++;
OrigLength++;
}
buf += ')';
OrigLength++;
if (PointerTypeTakesAnyBlockArguments(DeclT) ||
PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
// Replace the '^' with '*' for arguments.
// Replace id with id/*<>*/
DeclLoc = ND->getLocation();
startBuf = SM->getCharacterData(DeclLoc);
const char *argListBegin, *argListEnd;
GetExtentOfArgList(startBuf, argListBegin, argListEnd);
while (argListBegin < argListEnd) {
if (*argListBegin == '^')
buf += '*';
else if (*argListBegin == '<') {
buf += "/*";
buf += *argListBegin++;
OrigLength++;;
while (*argListBegin != '>') {
buf += *argListBegin++;
OrigLength++;
}
buf += *argListBegin;
buf += "*/";
}
else
buf += *argListBegin;
argListBegin++;
OrigLength++;
}
buf += ')';
OrigLength++;
}
ReplaceText(Start, OrigLength, buf);
return;
}
/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
/// struct Block_byref_id_object *src) {
/// _Block_object_assign (&_dest->object, _src->object,
/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
/// [|BLOCK_FIELD_IS_WEAK]) // object
/// _Block_object_assign(&_dest->object, _src->object,
/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
/// [|BLOCK_FIELD_IS_WEAK]) // block
/// }
/// And:
/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
/// _Block_object_dispose(_src->object,
/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
/// [|BLOCK_FIELD_IS_WEAK]) // object
/// _Block_object_dispose(_src->object,
/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
/// [|BLOCK_FIELD_IS_WEAK]) // block
/// }
std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
int flag) {
std::string S;
if (CopyDestroyCache.count(flag))
return S;
CopyDestroyCache.insert(flag);
S = "static void __Block_byref_id_object_copy_";
S += utostr(flag);
S += "(void *dst, void *src) {\n";
// offset into the object pointer is computed as:
// void * + void* + int + int + void* + void *
unsigned IntSize =
static_cast(Context->getTypeSize(Context->IntTy));
unsigned VoidPtrSize =
static_cast(Context->getTypeSize(Context->VoidPtrTy));
unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
S += " _Block_object_assign((char*)dst + ";
S += utostr(offset);
S += ", *(void * *) ((char*)src + ";
S += utostr(offset);
S += "), ";
S += utostr(flag);
S += ");\n}\n";
S += "static void __Block_byref_id_object_dispose_";
S += utostr(flag);
S += "(void *src) {\n";
S += " _Block_object_dispose(*(void * *) ((char*)src + ";
S += utostr(offset);
S += "), ";
S += utostr(flag);
S += ");\n}\n";
return S;
}
/// RewriteByRefVar - For each __block typex ND variable this routine transforms
/// the declaration into:
/// struct __Block_byref_ND {
/// void *__isa; // NULL for everything except __weak pointers
/// struct __Block_byref_ND *__forwarding;
/// int32_t __flags;
/// int32_t __size;
/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
/// typex ND;
/// };
///
/// It then replaces declaration of ND variable with:
/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
/// __size=sizeof(struct __Block_byref_ND),
/// ND=initializer-if-any};
///
///
void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
// Insert declaration for the function in which block literal is
// used.
if (CurFunctionDeclToDeclareForBlock)
RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
int flag = 0;
int isa = 0;
SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
if (DeclLoc.isInvalid())
// If type location is missing, it is because of missing type (a warning).
// Use variable's location which is good for this case.
DeclLoc = ND->getLocation();
const char *startBuf = SM->getCharacterData(DeclLoc);
SourceLocation X = ND->getLocEnd();
X = SM->getExpansionLoc(X);
const char *endBuf = SM->getCharacterData(X);
std::string Name(ND->getNameAsString());
std::string ByrefType;
RewriteByRefString(ByrefType, Name, ND, true);
ByrefType += " {\n";
ByrefType += " void *__isa;\n";
RewriteByRefString(ByrefType, Name, ND);
ByrefType += " *__forwarding;\n";
ByrefType += " int __flags;\n";
ByrefType += " int __size;\n";
// Add void *__Block_byref_id_object_copy;
// void *__Block_byref_id_object_dispose; if needed.
QualType Ty = ND->getType();
bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
if (HasCopyAndDispose) {
ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
}
QualType T = Ty;
(void)convertBlockPointerToFunctionPointer(T);
T.getAsStringInternal(Name, Context->getPrintingPolicy());
ByrefType += " " + Name + ";\n";
ByrefType += "};\n";
// Insert this type in global scope. It is needed by helper function.
SourceLocation FunLocStart;
if (CurFunctionDef)
FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
else {
assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
FunLocStart = CurMethodDef->getLocStart();
}
InsertText(FunLocStart, ByrefType);
if (Ty.isObjCGCWeak()) {
flag |= BLOCK_FIELD_IS_WEAK;
isa = 1;
}
if (HasCopyAndDispose) {
flag = BLOCK_BYREF_CALLER;
QualType Ty = ND->getType();
// FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
if (Ty->isBlockPointerType())
flag |= BLOCK_FIELD_IS_BLOCK;
else
flag |= BLOCK_FIELD_IS_OBJECT;
std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
if (!HF.empty())
InsertText(FunLocStart, HF);
}
// struct __Block_byref_ND ND =
// {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
// initializer-if-any};
bool hasInit = (ND->getInit() != 0);
unsigned flags = 0;
if (HasCopyAndDispose)
flags |= BLOCK_HAS_COPY_DISPOSE;
Name = ND->getNameAsString();
ByrefType.clear();
RewriteByRefString(ByrefType, Name, ND);
std::string ForwardingCastType("(");
ForwardingCastType += ByrefType + " *)";
if (!hasInit) {
ByrefType += " " + Name + " = {(void*)";
ByrefType += utostr(isa);
ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
ByrefType += utostr(flags);
ByrefType += ", ";
ByrefType += "sizeof(";
RewriteByRefString(ByrefType, Name, ND);
ByrefType += ")";
if (HasCopyAndDispose) {
ByrefType += ", __Block_byref_id_object_copy_";
ByrefType += utostr(flag);
ByrefType += ", __Block_byref_id_object_dispose_";
ByrefType += utostr(flag);
}
ByrefType += "};\n";
unsigned nameSize = Name.size();
// for block or function pointer declaration. Name is aleady
// part of the declaration.
if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
nameSize = 1;
ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
}
else {
SourceLocation startLoc;
Expr *E = ND->getInit();
if (const CStyleCastExpr *ECE = dyn_cast(E))
startLoc = ECE->getLParenLoc();
else
startLoc = E->getLocStart();
startLoc = SM->getExpansionLoc(startLoc);
endBuf = SM->getCharacterData(startLoc);
ByrefType += " " + Name;
ByrefType += " = {(void*)";
ByrefType += utostr(isa);
ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
ByrefType += utostr(flags);
ByrefType += ", ";
ByrefType += "sizeof(";
RewriteByRefString(ByrefType, Name, ND);
ByrefType += "), ";
if (HasCopyAndDispose) {
ByrefType += "__Block_byref_id_object_copy_";
ByrefType += utostr(flag);
ByrefType += ", __Block_byref_id_object_dispose_";
ByrefType += utostr(flag);
ByrefType += ", ";
}
ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
// Complete the newly synthesized compound expression by inserting a right
// curly brace before the end of the declaration.
// FIXME: This approach avoids rewriting the initializer expression. It
// also assumes there is only one declarator. For example, the following
// isn't currently supported by this routine (in general):
//
// double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
//
const char *startInitializerBuf = SM->getCharacterData(startLoc);
const char *semiBuf = strchr(startInitializerBuf, ';');
assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
SourceLocation semiLoc =
startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
InsertText(semiLoc, "}");
}
return;
}
void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
// Add initializers for any closure decl refs.
GetBlockDeclRefExprs(Exp->getBody());
if (BlockDeclRefs.size()) {
// Unique all "by copy" declarations.
for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
if (!BlockDeclRefs[i]->getDecl()->hasAttr()) {
if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
}
}
// Unique all "by ref" declarations.
for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
if (BlockDeclRefs[i]->getDecl()->hasAttr()) {
if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
}
}
// Find any imported blocks...they will need special attention.
for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
if (BlockDeclRefs[i]->getDecl()->hasAttr() ||
BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
BlockDeclRefs[i]->getType()->isBlockPointerType())
ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
}
}
FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
IdentifierInfo *ID = &Context->Idents.get(name);
QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
SourceLocation(), ID, FType, 0, SC_Extern,
SC_None, false, false);
}
Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
const SmallVector &InnerBlockDeclRefs) {
const BlockDecl *block = Exp->getBlockDecl();
Blocks.push_back(Exp);
CollectBlockDeclRefInfo(Exp);
// Add inner imported variables now used in current block.
int countOfInnerDecls = 0;
if (!InnerBlockDeclRefs.empty()) {
for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
DeclRefExpr *Exp = InnerBlockDeclRefs[i];
ValueDecl *VD = Exp->getDecl();
if (!VD->hasAttr() && !BlockByCopyDeclsPtrSet.count(VD)) {
// We need to save the copied-in variables in nested
// blocks because it is needed at the end for some of the API generations.
// See SynthesizeBlockLiterals routine.
InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
BlockDeclRefs.push_back(Exp);
BlockByCopyDeclsPtrSet.insert(VD);
BlockByCopyDecls.push_back(VD);
}
if (VD->hasAttr() && !BlockByRefDeclsPtrSet.count(VD)) {
InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
BlockDeclRefs.push_back(Exp);
BlockByRefDeclsPtrSet.insert(VD);
BlockByRefDecls.push_back(VD);
}
}
// Find any imported blocks...they will need special attention.
for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
if (InnerBlockDeclRefs[i]->getDecl()->hasAttr() ||
InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
}
InnerDeclRefsCount.push_back(countOfInnerDecls);
std::string FuncName;
if (CurFunctionDef)
FuncName = CurFunctionDef->getNameAsString();
else if (CurMethodDef)
BuildUniqueMethodName(FuncName, CurMethodDef);
else if (GlobalVarDecl)
FuncName = std::string(GlobalVarDecl->getNameAsString());
std::string BlockNumber = utostr(Blocks.size()-1);
std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
// Get a pointer to the function type so we can cast appropriately.
QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
QualType FType = Context->getPointerType(BFT);
FunctionDecl *FD;
Expr *NewRep;
// Simulate a contructor call...
FD = SynthBlockInitFunctionDecl(Tag);
DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
SourceLocation());
SmallVector InitExprs;
// Initialize the block function.
FD = SynthBlockInitFunctionDecl(Func);
DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
VK_LValue, SourceLocation());
CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
CK_BitCast, Arg);
InitExprs.push_back(castExpr);
// Initialize the block descriptor.
std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
SourceLocation(), SourceLocation(),
&Context->Idents.get(DescData.c_str()),
Context->VoidPtrTy, 0,
SC_Static, SC_None);
UnaryOperator *DescRefExpr =
new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Context->VoidPtrTy,
VK_LValue,
SourceLocation()),
UO_AddrOf,
Context->getPointerType(Context->VoidPtrTy),
VK_RValue, OK_Ordinary,
SourceLocation());
InitExprs.push_back(DescRefExpr);
// Add initializers for any closure decl refs.
if (BlockDeclRefs.size()) {
Expr *Exp;
// Output all "by copy" declarations.
for (SmallVector::iterator I = BlockByCopyDecls.begin(),
E = BlockByCopyDecls.end(); I != E; ++I) {
if (isObjCType((*I)->getType())) {
// FIXME: Conform to ABI ([[obj retain] autorelease]).
FD = SynthBlockInitFunctionDecl((*I)->getName());
Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
SourceLocation());
if (HasLocalVariableExternalStorage(*I)) {
QualType QT = (*I)->getType();
QT = Context->getPointerType(QT);
Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
OK_Ordinary, SourceLocation());
}
} else if (isTopLevelBlockPointerType((*I)->getType())) {
FD = SynthBlockInitFunctionDecl((*I)->getName());
Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
SourceLocation());
Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
CK_BitCast, Arg);
} else {
FD = SynthBlockInitFunctionDecl((*I)->getName());
Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
SourceLocation());
if (HasLocalVariableExternalStorage(*I)) {
QualType QT = (*I)->getType();
QT = Context->getPointerType(QT);
Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
OK_Ordinary, SourceLocation());
}
}
InitExprs.push_back(Exp);
}
// Output all "by ref" declarations.
for (SmallVector::iterator I = BlockByRefDecls.begin(),
E = BlockByRefDecls.end(); I != E; ++I) {
ValueDecl *ND = (*I);
std::string Name(ND->getNameAsString());
std::string RecName;
RewriteByRefString(RecName, Name, ND, true);
IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
+ sizeof("struct"));
RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
SourceLocation(), SourceLocation(),
II);
assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
FD = SynthBlockInitFunctionDecl((*I)->getName());
Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
SourceLocation());
bool isNestedCapturedVar = false;
if (block)
for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
ce = block->capture_end(); ci != ce; ++ci) {
const VarDecl *variable = ci->getVariable();
if (variable == ND && ci->isNested()) {
assert (ci->isByRef() &&
"SynthBlockInitExpr - captured block variable is not byref");
isNestedCapturedVar = true;
break;
}
}
// captured nested byref variable has its address passed. Do not take
// its address again.
if (!isNestedCapturedVar)
Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Context->getPointerType(Exp->getType()),
VK_RValue, OK_Ordinary, SourceLocation());
Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
InitExprs.push_back(Exp);
}
}
if (ImportedBlockDecls.size()) {
// generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
unsigned IntSize =
static_cast(Context->getTypeSize(Context->IntTy));
Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
Context->IntTy, SourceLocation());
InitExprs.push_back(FlagExp);
}
NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
FType, VK_LValue, SourceLocation());
NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Context->getPointerType(NewRep->getType()),
VK_RValue, OK_Ordinary, SourceLocation());
NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
NewRep);
BlockDeclRefs.clear();
BlockByRefDecls.clear();
BlockByRefDeclsPtrSet.clear();
BlockByCopyDecls.clear();
BlockByCopyDeclsPtrSet.clear();
ImportedBlockDecls.clear();
return NewRep;
}
bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
if (const ObjCForCollectionStmt * CS =
dyn_cast(Stmts.back()))
return CS->getElement() == DS;
return false;
}
//===----------------------------------------------------------------------===//
// Function Body / Expression rewriting
//===----------------------------------------------------------------------===//
Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
if (isa(S) || isa(S) ||
isa(S) || isa(S))
Stmts.push_back(S);
else if (isa(S)) {
Stmts.push_back(S);
ObjCBcLabelNo.push_back(++BcLabelCount);
}
// Pseudo-object operations and ivar references need special
// treatment because we're going to recursively rewrite them.
if (PseudoObjectExpr *PseudoOp = dyn_cast(S)) {
if (isa(PseudoOp->getSyntacticForm())) {
return RewritePropertyOrImplicitSetter(PseudoOp);
} else {
return RewritePropertyOrImplicitGetter(PseudoOp);
}
} else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast(S)) {
return RewriteObjCIvarRefExpr(IvarRefExpr);
}
SourceRange OrigStmtRange = S->getSourceRange();
// Perform a bottom up rewrite of all children.
for (Stmt::child_range CI = S->children(); CI; ++CI)
if (*CI) {
Stmt *childStmt = (*CI);
Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
if (newStmt) {
*CI = newStmt;
}
}
if (BlockExpr *BE = dyn_cast(S)) {
SmallVector InnerBlockDeclRefs;
llvm::SmallPtrSet InnerContexts;
InnerContexts.insert(BE->getBlockDecl());
ImportedLocalExternalDecls.clear();
GetInnerBlockDeclRefExprs(BE->getBody(),
InnerBlockDeclRefs, InnerContexts);
// Rewrite the block body in place.
Stmt *SaveCurrentBody = CurrentBody;
CurrentBody = BE->getBody();
PropParentMap = 0;
// block literal on rhs of a property-dot-sytax assignment
// must be replaced by its synthesize ast so getRewrittenText
// works as expected. In this case, what actually ends up on RHS
// is the blockTranscribed which is the helper function for the
// block literal; as in: self.c = ^() {[ace ARR];};
bool saveDisableReplaceStmt = DisableReplaceStmt;
DisableReplaceStmt = false;
RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
DisableReplaceStmt = saveDisableReplaceStmt;
CurrentBody = SaveCurrentBody;
PropParentMap = 0;
ImportedLocalExternalDecls.clear();
// Now we snarf the rewritten text and stash it away for later use.
std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
RewrittenBlockExprs[BE] = Str;
Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
//blockTranscribed->dump();
ReplaceStmt(S, blockTranscribed);
return blockTranscribed;
}
// Handle specific things.
if (ObjCEncodeExpr *AtEncode = dyn_cast(S))
return RewriteAtEncode(AtEncode);
if (ObjCSelectorExpr *AtSelector = dyn_cast(S))
return RewriteAtSelector(AtSelector);
if (ObjCStringLiteral *AtString = dyn_cast(S))
return RewriteObjCStringLiteral(AtString);
if (ObjCMessageExpr *MessExpr = dyn_cast(S)) {
#if 0
// Before we rewrite it, put the original message expression in a comment.
SourceLocation startLoc = MessExpr->getLocStart();
SourceLocation endLoc = MessExpr->getLocEnd();
const char *startBuf = SM->getCharacterData(startLoc);
const char *endBuf = SM->getCharacterData(endLoc);
std::string messString;
messString += "// ";
messString.append(startBuf, endBuf-startBuf+1);
messString += "\n";
// FIXME: Missing definition of
// InsertText(clang::SourceLocation, char const*, unsigned int).
// InsertText(startLoc, messString.c_str(), messString.size());
// Tried this, but it didn't work either...
// ReplaceText(startLoc, 0, messString.c_str(), messString.size());
#endif
return RewriteMessageExpr(MessExpr);
}
if (ObjCAtTryStmt *StmtTry = dyn_cast(S))
return RewriteObjCTryStmt(StmtTry);
if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast(S))
return RewriteObjCSynchronizedStmt(StmtTry);
if (ObjCAtThrowStmt *StmtThrow = dyn_cast(S))
return RewriteObjCThrowStmt(StmtThrow);
if (ObjCProtocolExpr *ProtocolExp = dyn_cast(S))
return RewriteObjCProtocolExpr(ProtocolExp);
if (ObjCForCollectionStmt *StmtForCollection =
dyn_cast(S))
return RewriteObjCForCollectionStmt(StmtForCollection,
OrigStmtRange.getEnd());
if (BreakStmt *StmtBreakStmt =
dyn_cast(S))
return RewriteBreakStmt(StmtBreakStmt);
if (ContinueStmt *StmtContinueStmt =
dyn_cast(S))
return RewriteContinueStmt(StmtContinueStmt);
// Need to check for protocol refs (id , Foo
*) in variable decls
// and cast exprs.
if (DeclStmt *DS = dyn_cast(S)) {
// FIXME: What we're doing here is modifying the type-specifier that
// precedes the first Decl. In the future the DeclGroup should have
// a separate type-specifier that we can rewrite.
// NOTE: We need to avoid rewriting the DeclStmt if it is within
// the context of an ObjCForCollectionStmt. For example:
// NSArray *someArray;
// for (id index in someArray) ;
// This is because RewriteObjCForCollectionStmt() does textual rewriting
// and it depends on the original text locations/positions.
if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
// Blocks rewrite rules.
for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
DI != DE; ++DI) {
Decl *SD = *DI;
if (ValueDecl *ND = dyn_cast(SD)) {
if (isTopLevelBlockPointerType(ND->getType()))
RewriteBlockPointerDecl(ND);
else if (ND->getType()->isFunctionPointerType())
CheckFunctionPointerDecl(ND->getType(), ND);
if (VarDecl *VD = dyn_cast(SD)) {
if (VD->hasAttr()) {
static unsigned uniqueByrefDeclCount = 0;
assert(!BlockByRefDeclNo.count(ND) &&
"RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
RewriteByRefVar(VD);
}
else
RewriteTypeOfDecl(VD);
}
}
if (TypedefNameDecl *TD = dyn_cast(SD)) {
if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
RewriteBlockPointerDecl(TD);
else if (TD->getUnderlyingType()->isFunctionPointerType())
CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
}
}
}
if (CStyleCastExpr *CE = dyn_cast(S))
RewriteObjCQualifiedInterfaceTypes(CE);
if (isa