blob: bc855fa87912d9be91728bc04c691f4772ff3ad3 [file] [log] [blame]
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001//===--- RewriteBlocks.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the closure rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Steve Naroff1c9f81b2008-09-17 00:13:27 +000015#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/Support/MemoryBuffer.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include <sstream>
26
27using namespace clang;
28using llvm::utostr;
29
30namespace {
31
32class RewriteBlocks : public ASTConsumer {
33 Rewriter Rewrite;
34 Diagnostic &Diags;
35 const LangOptions &LangOpts;
36 unsigned RewriteFailedDiag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000037
38 ASTContext *Context;
39 SourceManager *SM;
Chris Lattner2b2453a2009-01-17 06:22:33 +000040 FileID MainFileID;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000041 const char *MainFileStart, *MainFileEnd;
42
43 // Block expressions.
44 llvm::SmallVector<BlockExpr *, 32> Blocks;
45 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
46 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
47
48 // Block related declarations.
49 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
50 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Steve Naroff4e13b762008-10-03 20:28:15 +000051 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Steve Naroff70f95502008-10-04 17:06:23 +000052
53 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000054
55 // The function/method we are rewriting.
56 FunctionDecl *CurFunctionDef;
57 ObjCMethodDecl *CurMethodDef;
58
59 bool IsHeader;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000060
61 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000062public:
Eli Friedman66d6f042009-05-18 22:20:00 +000063 RewriteBlocks(std::string inFile, Diagnostic &D,
Steve Naroff13188952008-09-18 14:10:13 +000064 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000065 ~RewriteBlocks() {
66 // Get the buffer corresponding to MainFileID.
67 // If we haven't changed it, then we are done.
68 if (const RewriteBuffer *RewriteBuf =
69 Rewrite.getRewriteBufferFor(MainFileID)) {
70 std::string S(RewriteBuf->begin(), RewriteBuf->end());
71 printf("%s\n", S.c_str());
72 } else {
73 printf("No changes\n");
74 }
75 }
76
77 void Initialize(ASTContext &context);
78
79 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
80 void ReplaceText(SourceLocation Start, unsigned OrigLength,
81 const char *NewStr, unsigned NewLength);
82
83 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +000084 virtual void HandleTopLevelDecl(DeclGroupRef D) {
85 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
86 HandleTopLevelSingleDecl(*I);
87 }
88 void HandleTopLevelSingleDecl(Decl *D);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000089 void HandleDeclInMainFile(Decl *D);
90
91 // Top level
92 Stmt *RewriteFunctionBody(Stmt *S);
93 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
94 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
95
96 // Block specific rewrite rules.
Steve Naroff70f95502008-10-04 17:06:23 +000097 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000098
99 void RewriteBlockCall(CallExpr *Exp);
100 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff5e52b172008-10-04 18:52:47 +0000101 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000102 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
103
Steve Naroff4e13b762008-10-03 20:28:15 +0000104 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
105 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000106 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
107 const char *funcName, std::string Tag);
Steve Naroffacba0f22008-10-04 23:47:37 +0000108 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
109 bool hasCopyDisposeHelpers);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000110 std::string SynthesizeBlockCall(CallExpr *Exp);
111 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
112 const char *FunName);
113
Steve Naroffd3f77902008-10-05 00:06:12 +0000114 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000115 void GetBlockCallExprs(Stmt *S);
Steve Naroffacba0f22008-10-04 23:47:37 +0000116 void GetBlockDeclRefExprs(Stmt *S);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000117
118 // We avoid calling Type::isBlockPointerType(), since it operates on the
119 // canonical type. We only care if the top-level type is a closure pointer.
120 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
121
122 // FIXME: This predicate seems like it would be useful to add to ASTContext.
123 bool isObjCType(QualType T) {
124 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
125 return false;
126
127 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
128
129 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
130 OCT == Context->getCanonicalType(Context->getObjCClassType()))
131 return true;
132
133 if (const PointerType *PT = OCT->getAsPointerType()) {
134 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000135 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000136 return true;
137 }
138 return false;
139 }
140 // ObjC rewrite methods.
141 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
142 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
143 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
144 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffca743602008-10-15 18:38:58 +0000145
Douglas Gregor72564e72009-02-26 23:50:07 +0000146 void RewriteFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroffca743602008-10-15 18:38:58 +0000147 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
148 void RewriteCastExpr(CastExpr *CE);
Steve Naroffeab5f632008-09-23 19:24:41 +0000149
Steve Naroffca743602008-10-15 18:38:58 +0000150 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000151 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000152};
153
154}
155
156static bool IsHeaderFile(const std::string &Filename) {
157 std::string::size_type DotPos = Filename.rfind('.');
158
159 if (DotPos == std::string::npos) {
160 // no file extension
161 return false;
162 }
163
164 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
165 // C header: .h
166 // C++ header: .hh or .H;
167 return Ext == "h" || Ext == "hh" || Ext == "H";
168}
169
Eli Friedman66d6f042009-05-18 22:20:00 +0000170RewriteBlocks::RewriteBlocks(std::string inFile,
Steve Naroff13188952008-09-18 14:10:13 +0000171 Diagnostic &D, const LangOptions &LOpts) :
172 Diags(D), LangOpts(LOpts) {
173 IsHeader = IsHeaderFile(inFile);
Steve Naroff13188952008-09-18 14:10:13 +0000174 CurFunctionDef = 0;
175 CurMethodDef = 0;
176 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
177 "rewriting failed");
Steve Naroff13188952008-09-18 14:10:13 +0000178}
179
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000180ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
181 Diagnostic &Diags,
182 const LangOptions &LangOpts) {
Eli Friedman66d6f042009-05-18 22:20:00 +0000183 return new RewriteBlocks(InFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000184}
185
186void RewriteBlocks::Initialize(ASTContext &context) {
187 Context = &context;
188 SM = &Context->getSourceManager();
189
190 // Get the ID and start/end of the main file.
191 MainFileID = SM->getMainFileID();
192 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
193 MainFileStart = MainBuf->getBufferStart();
194 MainFileEnd = MainBuf->getBufferEnd();
195
Chris Lattner2c78b872009-04-14 23:22:57 +0000196 Rewrite.setSourceMgr(Context->getSourceManager(), LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000197
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000198 if (IsHeader)
199 Preamble = "#pragma once\n";
200 Preamble += "#ifndef BLOCK_IMPL\n";
201 Preamble += "#define BLOCK_IMPL\n";
202 Preamble += "struct __block_impl {\n";
203 Preamble += " void *isa;\n";
204 Preamble += " int Flags;\n";
205 Preamble += " int Size;\n";
206 Preamble += " void *FuncPtr;\n";
207 Preamble += "};\n";
208 Preamble += "enum {\n";
209 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
210 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
211 Preamble += "};\n";
212 if (LangOpts.Microsoft)
213 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
214 else
215 Preamble += "#define __OBJC_RW_EXTERN extern\n";
216 Preamble += "// Runtime copy/destroy helper functions\n";
217 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
218 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
219 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
220 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000221 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
222 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000223 Preamble += "#endif\n";
224
Chris Lattner2b2453a2009-01-17 06:22:33 +0000225 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000226 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000227}
228
229void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
230 unsigned StrLen)
231{
232 if (!Rewrite.InsertText(Loc, StrData, StrLen))
233 return;
234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235}
236
237void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
238 const char *NewStr, unsigned NewLength) {
239 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
240 return;
241 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
242}
243
244void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
245 bool haveBlockPtrs = false;
246 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
247 E = Method->param_end(); I != E; ++I)
248 if (isBlockPointerType((*I)->getType()))
249 haveBlockPtrs = true;
250
251 if (!haveBlockPtrs)
252 return;
253
254 // Do a fuzzy rewrite.
255 // We have 1 or more arguments that have closure pointers.
256 SourceLocation Loc = Method->getLocStart();
257 SourceLocation LocEnd = Method->getLocEnd();
258 const char *startBuf = SM->getCharacterData(Loc);
259 const char *endBuf = SM->getCharacterData(LocEnd);
260
261 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000262 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000263
264 while (*methodPtr++ && (methodPtr != endBuf)) {
265 switch (*methodPtr) {
266 case ':':
267 methodPtr++;
268 if (*methodPtr == '(') {
269 const char *scanType = ++methodPtr;
270 bool foundBlockPointer = false;
271 unsigned parenCount = 1;
272
273 while (parenCount) {
274 switch (*scanType) {
275 case '(':
276 parenCount++;
277 break;
278 case ')':
279 parenCount--;
280 break;
281 case '^':
282 foundBlockPointer = true;
283 break;
284 }
285 scanType++;
286 }
287 if (foundBlockPointer) {
288 // advance the location to startArgList.
289 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
290 assert((Loc.isValid()) && "Invalid Loc");
291 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
292
293 // Advance startBuf. Since the underlying buffer has changed,
294 // it's very important to advance startBuf (so we can correctly
295 // compute a relative Loc the next time around).
296 startBuf = methodPtr;
297 }
298 // Advance the method ptr to the end of the type.
299 methodPtr = scanType;
300 }
301 break;
302 }
303 }
304 return;
305}
306
307void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000308 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000309 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000310 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000311 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000312 for (ObjCInterfaceDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000313 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000314 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000315 RewriteMethodDecl(*I);
316}
317
318void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000319 for (ObjCCategoryDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000320 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000321 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000322 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000323 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000324 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000325 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000326 RewriteMethodDecl(*I);
327}
328
329void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000330 for (ObjCProtocolDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000331 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000332 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000333 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000334 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000335 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000336 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000337 RewriteMethodDecl(*I);
338}
339
340//===----------------------------------------------------------------------===//
341// Top Level Driver Code
342//===----------------------------------------------------------------------===//
343
Chris Lattner682bf922009-03-29 16:50:03 +0000344void RewriteBlocks::HandleTopLevelSingleDecl(Decl *D) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000345 // Two cases: either the decl could be in the main file, or it could be in a
346 // #included file. If the former, rewrite it now. If the later, check to see
347 // if we rewrote the #include/#import.
348 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000349 Loc = SM->getInstantiationLoc(Loc);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000350
351 // If this is for a builtin, ignore it.
352 if (Loc.isInvalid()) return;
353
354 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
355 RewriteInterfaceDecl(MD);
356 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
357 RewriteCategoryDecl(CD);
358 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
359 RewriteProtocolDecl(PD);
360
361 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner23f2c582009-01-25 22:02:19 +0000362 if (SM->isFromMainFile(Loc))
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000363 HandleDeclInMainFile(D);
364 return;
365}
366
367std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
368 const char *funcName,
369 std::string Tag) {
370 const FunctionType *AFT = CE->getFunctionType();
371 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000372 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000373 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000374 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000375
Steve Naroff56ee6892008-10-08 17:01:13 +0000376 BlockDecl *BD = CE->getBlockDecl();
377
Douglas Gregor72564e72009-02-26 23:50:07 +0000378 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000379 S += "()";
Steve Naroff56ee6892008-10-08 17:01:13 +0000380 } else if (BD->param_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000381 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000382 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +0000383 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000384 assert(FT && "SynthesizeBlockFunc: No function proto");
385 S += '(';
386 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000387 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000388 std::string ParamStr;
Steve Naroff56ee6892008-10-08 17:01:13 +0000389 for (BlockDecl::param_iterator AI = BD->param_begin(),
390 E = BD->param_end(); AI != E; ++AI) {
391 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000392 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000393 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000394 S += ParamStr;
395 }
396 if (FT->isVariadic()) {
Steve Naroff56ee6892008-10-08 17:01:13 +0000397 if (!BD->param_empty()) S += ", ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000398 S += "...";
399 }
400 S += ')';
401 }
402 S += " {\n";
403
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000404 // Create local declarations to avoid rewriting all closure decl ref exprs.
405 // First, emit a declaration for all "by ref" decls.
406 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
407 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000408 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000409 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000410 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
411 Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000412 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000413 }
414 // Next, emit a declaration for all "by copy" declarations.
415 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
416 E = BlockByCopyDecls.end(); I != E; ++I) {
417 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000418 std::string Name = (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000419 // Handle nested closure invocation. For example:
420 //
421 // void (^myImportedClosure)(void);
422 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
423 //
424 // void (^anotherClosure)(void);
425 // anotherClosure = ^(void) {
426 // myImportedClosure(); // import and invoke the closure
427 // };
428 //
429 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000430 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000431 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000432 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000433 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000434 }
Steve Naroff70f95502008-10-04 17:06:23 +0000435 std::string RewrittenStr = RewrittenBlockExprs[CE];
436 const char *cstr = RewrittenStr.c_str();
437 while (*cstr++ != '{') ;
438 S += cstr;
439 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000440 return S;
441}
442
Steve Naroff4e13b762008-10-03 20:28:15 +0000443std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
444 const char *funcName,
445 std::string Tag) {
446 std::string StructRef = "struct " + Tag;
447 std::string S = "static void __";
448
449 S += funcName;
450 S += "_block_copy_" + utostr(i);
451 S += "(" + StructRef;
452 S += "*dst, " + StructRef;
453 S += "*src) {";
454 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
455 E = ImportedBlockDecls.end(); I != E; ++I) {
456 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000457 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000458 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000459 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000460 S += ");}";
461 }
462 S += "\nstatic void __";
463 S += funcName;
464 S += "_block_dispose_" + utostr(i);
465 S += "(" + StructRef;
466 S += "*src) {";
467 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
468 E = ImportedBlockDecls.end(); I != E; ++I) {
469 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000470 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000471 S += ");";
472 }
473 S += "}\n";
474 return S;
475}
476
Steve Naroffacba0f22008-10-04 23:47:37 +0000477std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
478 bool hasCopyDisposeHelpers) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000479 std::string S = "struct " + Tag;
480 std::string Constructor = " " + Tag;
481
482 S += " {\n struct __block_impl impl;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000483
484 if (hasCopyDisposeHelpers)
485 S += " void *copy;\n void *dispose;\n";
486
Steve Naroff48a8c612008-10-03 12:09:49 +0000487 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000488
Steve Naroffacba0f22008-10-04 23:47:37 +0000489 if (hasCopyDisposeHelpers)
490 Constructor += ", void *copyHelp, void *disposeHelp";
491
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000492 if (BlockDeclRefs.size()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000493 // Output all "by copy" declarations.
494 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
495 E = BlockByCopyDecls.end(); I != E; ++I) {
496 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000497 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000498 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000499 // Handle nested closure invocation. For example:
500 //
501 // void (^myImportedBlock)(void);
502 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
503 //
504 // void (^anotherBlock)(void);
505 // anotherBlock = ^(void) {
506 // myImportedBlock(); // import and invoke the closure
507 // };
508 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000509 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000510 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000511 Constructor += ", void *" + ArgName;
512 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000513 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
514 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff4e13b762008-10-03 20:28:15 +0000515 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000516 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000517 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000518 }
519 // Output all "by ref" declarations.
520 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
521 E = BlockByRefDecls.end(); I != E; ++I) {
522 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000523 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000524 std::string ArgName = "_" + FieldName;
525 // Handle nested closure invocation. For example:
526 //
527 // void (^myImportedBlock)(void);
528 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
529 //
530 // void (^anotherBlock)(void);
531 // anotherBlock = ^(void) {
532 // myImportedBlock(); // import and invoke the closure
533 // };
534 //
535 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000536 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000537 Constructor += ", void *" + ArgName;
538 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000539 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
540 Context->PrintingPolicy);
541 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
542 Context->PrintingPolicy);
Steve Naroff4e13b762008-10-03 20:28:15 +0000543 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000544 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000545 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000546 }
547 // Finish writing the constructor.
548 // FIXME: handle NSConcreteGlobalBlock.
549 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000550 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000551 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
552
Steve Naroffacba0f22008-10-04 23:47:37 +0000553 if (hasCopyDisposeHelpers)
554 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
555
Steve Naroff48a8c612008-10-03 12:09:49 +0000556 // Initialize all "by copy" arguments.
557 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
558 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000559 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000560 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000561 if (isBlockPointerType((*I)->getType()))
562 Constructor += Name + " = (struct __block_impl *)_";
563 else
564 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000565 Constructor += Name + ";\n";
566 }
567 // Initialize all "by ref" arguments.
568 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
569 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000570 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000571 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000572 if (isBlockPointerType((*I)->getType()))
573 Constructor += Name + " = (struct __block_impl *)_";
574 else
575 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000576 Constructor += Name + ";\n";
577 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000578 } else {
579 // Finish writing the constructor.
580 // FIXME: handle NSConcreteGlobalBlock.
581 Constructor += ", int flags=0) {\n";
582 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
583 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000584 if (hasCopyDisposeHelpers)
585 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000586 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000587 Constructor += " ";
588 Constructor += "}\n";
589 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000590 S += "};\n";
591 return S;
592}
593
594void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
595 const char *FunName) {
596 // Insert closures that were part of the function.
597 for (unsigned i = 0; i < Blocks.size(); i++) {
Steve Naroffacba0f22008-10-04 23:47:37 +0000598
Steve Naroffd3f77902008-10-05 00:06:12 +0000599 CollectBlockDeclRefInfo(Blocks[i]);
600
Steve Naroff48a8c612008-10-03 12:09:49 +0000601 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000602
Steve Naroffacba0f22008-10-04 23:47:37 +0000603 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
604 ImportedBlockDecls.size() > 0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000605
606 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000607
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000608 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
609
610 InsertText(FunLocStart, CF.c_str(), CF.size());
611
Steve Naroff4e13b762008-10-03 20:28:15 +0000612 if (ImportedBlockDecls.size()) {
613 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
614 InsertText(FunLocStart, HF.c_str(), HF.size());
615 }
616
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000617 BlockDeclRefs.clear();
618 BlockByRefDecls.clear();
619 BlockByCopyDecls.clear();
620 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000621 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000622 }
623 Blocks.clear();
Steve Naroff8e9216d2008-10-04 17:10:02 +0000624 RewrittenBlockExprs.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000625}
626
627void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000628 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +0000629 const char *FuncName = FD->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000630
631 SynthesizeBlockLiterals(FunLocStart, FuncName);
632}
633
634void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
635 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattner077bf5e2008-11-24 03:33:13 +0000636 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000637 // Convert colons to underscores.
638 std::string::size_type loc = 0;
639 while ((loc = FuncName.find(":", loc)) != std::string::npos)
640 FuncName.replace(loc, 1, "_");
641
642 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
643}
644
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000645void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
646 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
647 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000648 if (*CI) {
649 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
650 GetBlockDeclRefExprs(CBE->getBody());
651 else
652 GetBlockDeclRefExprs(*CI);
653 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000654 // Handle specific things.
655 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
656 // FIXME: Handle enums.
657 if (!isa<FunctionDecl>(CDRE->getDecl()))
658 BlockDeclRefs.push_back(CDRE);
659 return;
660}
661
662void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
663 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
664 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000665 if (*CI) {
666 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
667 GetBlockCallExprs(CBE->getBody());
668 else
669 GetBlockCallExprs(*CI);
670 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000671
672 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000673 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000674 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000675 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000676 }
677 return;
678}
679
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000680std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
681 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000682 const char *closureName = 0;
683 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000684
685 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000686 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000687 CPT = DRE->getType()->getAsBlockPointerType();
688 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000689 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000690 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000691 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000692 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000693 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000694 } else {
695 assert(1 && "RewriteBlockClass: Bad type");
696 }
697 assert(CPT && "RewriteBlockClass: Bad type");
698 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
699 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000700 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000701 // FTP will be null for closures that don't take arguments.
702
703 // Build a closure call - start with a paren expr to enforce precedence.
704 std::string BlockCall = "(";
705
706 // Synthesize the cast.
707 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000708 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000709 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000710 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000711 E = FTP->arg_type_end(); I && (I != E); ++I)
712 BlockCall += ", " + (*I).getAsString();
713 }
714 BlockCall += "))"; // close the argument list and paren expression.
715
Steve Naroff83ba14e2008-10-03 15:04:50 +0000716 // Invoke the closure. We need to cast it since the declaration type is
717 // bogus (it's a function pointer type)
718 BlockCall += "((struct __block_impl *)";
719 std::string closureExprBufStr;
720 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000721 Exp->getCallee()->printPretty(closureExprBuf, *Context, 0,
722 PrintingPolicy(LangOpts));
Steve Naroff83ba14e2008-10-03 15:04:50 +0000723 BlockCall += closureExprBuf.str();
724 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000725
726 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000727 BlockCall += "((struct __block_impl *)";
Steve Naroffb65a4f12008-10-04 17:45:51 +0000728 BlockCall += closureExprBuf.str();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000729 for (CallExpr::arg_iterator I = Exp->arg_begin(),
730 E = Exp->arg_end(); I != E; ++I) {
731 std::string syncExprBufS;
732 llvm::raw_string_ostream Buf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +0000733 (*I)->printPretty(Buf, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000734 BlockCall += ", " + Buf.str();
735 }
736 return BlockCall;
737}
738
739void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
740 std::string BlockCall = SynthesizeBlockCall(Exp);
741
742 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
743 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
744
745 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
746 BlockCall.c_str(), BlockCall.size());
747}
748
Steve Naroff5e52b172008-10-04 18:52:47 +0000749void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
750 // FIXME: Add more elaborate code generation required by the ABI.
751 InsertText(BDRE->getLocStart(), "*", 1);
752}
753
Steve Naroffca743602008-10-15 18:38:58 +0000754void RewriteBlocks::RewriteCastExpr(CastExpr *CE) {
755 SourceLocation LocStart = CE->getLocStart();
756 SourceLocation LocEnd = CE->getLocEnd();
757
Steve Naroff8f6ce572008-11-03 11:20:24 +0000758 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
759 return;
760
Steve Naroffca743602008-10-15 18:38:58 +0000761 const char *startBuf = SM->getCharacterData(LocStart);
762 const char *endBuf = SM->getCharacterData(LocEnd);
763
764 // advance the location to startArgList.
765 const char *argPtr = startBuf;
766
767 while (*argPtr++ && (argPtr < endBuf)) {
768 switch (*argPtr) {
769 case '^':
770 // Replace the '^' with '*'.
771 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
772 ReplaceText(LocStart, 1, "*", 1);
773 break;
774 }
775 }
776 return;
777}
778
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000779void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
780 SourceLocation DeclLoc = FD->getLocation();
Steve Naroffe0109a52008-10-10 15:33:34 +0000781 unsigned parenCount = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000782
783 // We have 1 or more arguments that have closure pointers.
784 const char *startBuf = SM->getCharacterData(DeclLoc);
785 const char *startArgList = strchr(startBuf, '(');
786
787 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
788
789 parenCount++;
790 // advance the location to startArgList.
Steve Naroffe0109a52008-10-10 15:33:34 +0000791 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000792 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
793
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000794 const char *argPtr = startArgList;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000795
796 while (*argPtr++ && parenCount) {
797 switch (*argPtr) {
798 case '^':
Steve Naroffe0109a52008-10-10 15:33:34 +0000799 // Replace the '^' with '*'.
800 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
801 ReplaceText(DeclLoc, 1, "*", 1);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000802 break;
803 case '(':
804 parenCount++;
805 break;
806 case ')':
807 parenCount--;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000808 break;
809 }
810 }
811 return;
812}
813
Steve Naroffca743602008-10-15 18:38:58 +0000814bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000815 const FunctionProtoType *FTP;
Steve Naroffca743602008-10-15 18:38:58 +0000816 const PointerType *PT = QT->getAsPointerType();
817 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000818 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000819 } else {
820 const BlockPointerType *BPT = QT->getAsBlockPointerType();
821 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000822 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000823 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000824 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000825 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffeab5f632008-09-23 19:24:41 +0000826 E = FTP->arg_type_end(); I != E; ++I)
827 if (isBlockPointerType(*I))
828 return true;
829 }
830 return false;
831}
832
833void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000834 const char *&LParen, const char *&RParen) {
835 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000836 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
837
838 LParen = argPtr; // output the start.
839 argPtr++; // skip past the left paren.
840 unsigned parenCount = 1;
841
842 while (*argPtr && parenCount) {
843 switch (*argPtr) {
844 case '(': parenCount++; break;
845 case ')': parenCount--; break;
846 default: break;
847 }
848 if (parenCount) argPtr++;
849 }
850 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
851 RParen = argPtr; // output the end
852}
853
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000854void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000855 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
856 RewriteBlockPointerFunctionArgs(FD);
857 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000858 }
859 // Handle Variables and Typedefs.
860 SourceLocation DeclLoc = ND->getLocation();
861 QualType DeclT;
862 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
863 DeclT = VD->getType();
864 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
865 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000866 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
867 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000868 else
869 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000870
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000871 const char *startBuf = SM->getCharacterData(DeclLoc);
872 const char *endBuf = startBuf;
873 // scan backward (from the decl location) for the end of the previous decl.
874 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
875 startBuf--;
Steve Naroffca743602008-10-15 18:38:58 +0000876
877 // *startBuf != '^' if we are dealing with a pointer to function that
878 // may take block argument types (which will be handled below).
879 if (*startBuf == '^') {
880 // Replace the '^' with '*', computing a negative offset.
881 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
882 ReplaceText(DeclLoc, 1, "*", 1);
883 }
884 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000885 // Replace the '^' with '*' for arguments.
886 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000887 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000888 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000889 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
890 while (argListBegin < argListEnd) {
891 if (*argListBegin == '^') {
892 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
893 ReplaceText(CaretLoc, 1, "*", 1);
894 }
895 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000896 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000897 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000898 return;
899}
900
Steve Naroffd3f77902008-10-05 00:06:12 +0000901void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000902 // Add initializers for any closure decl refs.
Steve Naroff84a969f2008-10-08 17:31:13 +0000903 GetBlockDeclRefExprs(Exp->getBody());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000904 if (BlockDeclRefs.size()) {
905 // Unique all "by copy" declarations.
906 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
907 if (!BlockDeclRefs[i]->isByRef())
908 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
909 // Unique all "by ref" declarations.
910 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
911 if (BlockDeclRefs[i]->isByRef()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000912 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
913 }
Steve Naroffacba0f22008-10-04 23:47:37 +0000914 // Find any imported blocks...they will need special attention.
915 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
916 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
917 GetBlockCallExprs(Blocks[i]);
918 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
919 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000920 }
Steve Naroffd3f77902008-10-05 00:06:12 +0000921}
922
923std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
924 Blocks.push_back(Exp);
925
926 CollectBlockDeclRefInfo(Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000927 std::string FuncName;
928
929 if (CurFunctionDef)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000930 FuncName = std::string(CurFunctionDef->getNameAsString());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000931 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000932 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000933 // Convert colons to underscores.
934 std::string::size_type loc = 0;
935 while ((loc = FuncName.find(":", loc)) != std::string::npos)
936 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000937 } else if (VD)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000938 FuncName = std::string(VD->getNameAsString());
Steve Naroff39622b92008-10-03 15:38:09 +0000939
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000940 std::string BlockNumber = utostr(Blocks.size()-1);
941
Steve Naroff83ba14e2008-10-03 15:04:50 +0000942 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000943 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000944
Steve Naroff83ba14e2008-10-03 15:04:50 +0000945 std::string FunkTypeStr;
946
947 // Get a pointer to the function type so we can cast appropriately.
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000948 Context->getPointerType(QualType(Exp->getFunctionType(),0))
949 .getAsStringInternal(FunkTypeStr, Context->PrintingPolicy);
Steve Naroff83ba14e2008-10-03 15:04:50 +0000950
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000951 // Rewrite the closure block with a compound literal. The first cast is
952 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000953 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000954
Steve Naroff83ba14e2008-10-03 15:04:50 +0000955 Init += ")&" + Tag;
956
957 // Initialize the block function.
958 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000959
Steve Naroffacba0f22008-10-04 23:47:37 +0000960 if (ImportedBlockDecls.size()) {
961 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
962 Init += ",(void*)" + Buf;
963 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
964 Init += ",(void*)" + Buf;
965 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000966 // Add initializers for any closure decl refs.
967 if (BlockDeclRefs.size()) {
968 // Output all "by copy" declarations.
969 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
970 E = BlockByCopyDecls.end(); I != E; ++I) {
971 Init += ",";
972 if (isObjCType((*I)->getType())) {
973 Init += "[[";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000974 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000975 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000976 } else if (isBlockPointerType((*I)->getType())) {
977 Init += "(void *)";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000978 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000979 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000980 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000981 }
982 }
983 // Output all "by ref" declarations.
984 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
985 E = BlockByRefDecls.end(); I != E; ++I) {
986 Init += ",&";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000987 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000988 }
989 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000990 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000991 BlockDeclRefs.clear();
992 BlockByRefDecls.clear();
993 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000994 ImportedBlockDecls.clear();
995
Steve Naroff70f95502008-10-04 17:06:23 +0000996 return Init;
997}
998
999//===----------------------------------------------------------------------===//
1000// Function Body / Expression rewriting
1001//===----------------------------------------------------------------------===//
1002
1003Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
1004 // Start by rewriting all children.
1005 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1006 CI != E; ++CI)
1007 if (*CI) {
1008 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Eli Friedman687abff2009-06-08 04:24:21 +00001009 RewriteFunctionBody(CBE->getBody());
Steve Naroff70f95502008-10-04 17:06:23 +00001010
1011 // We've just rewritten the block body in place.
1012 // Now we snarf the rewritten text and stash it away for later use.
1013 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1014 RewrittenBlockExprs[CBE] = S;
1015 std::string Init = SynthesizeBlockInitExpr(CBE);
1016 // Do the rewrite, using S.size() which contains the rewritten size.
1017 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1018 } else {
Eli Friedman687abff2009-06-08 04:24:21 +00001019 RewriteFunctionBody(*CI);
Steve Naroff70f95502008-10-04 17:06:23 +00001020 }
1021 }
1022 // Handle specific things.
1023 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1024 if (CE->getCallee()->getType()->isBlockPointerType())
1025 RewriteBlockCall(CE);
1026 }
Steve Naroffca743602008-10-15 18:38:58 +00001027 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1028 RewriteCastExpr(CE);
1029 }
Steve Naroff70f95502008-10-04 17:06:23 +00001030 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001031 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1032 DI != DE; ++DI) {
1033
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001034 Decl *SD = *DI;
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001035 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1036 if (isBlockPointerType(ND->getType()))
1037 RewriteBlockPointerDecl(ND);
Steve Naroffca743602008-10-15 18:38:58 +00001038 else if (ND->getType()->isFunctionPointerType())
1039 CheckFunctionPointerDecl(ND->getType(), ND);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001040 }
1041 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1042 if (isBlockPointerType(TD->getUnderlyingType()))
1043 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001044 else if (TD->getUnderlyingType()->isFunctionPointerType())
1045 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001046 }
Steve Naroff70f95502008-10-04 17:06:23 +00001047 }
1048 }
Steve Naroff5e52b172008-10-04 18:52:47 +00001049 // Handle specific things.
1050 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1051 if (BDRE->isByRef())
1052 RewriteBlockDeclRefExpr(BDRE);
1053 }
Steve Naroff70f95502008-10-04 17:06:23 +00001054 // Return this stmt unmodified.
1055 return S;
1056}
1057
Douglas Gregor72564e72009-02-26 23:50:07 +00001058void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) {
1059 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
1060 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroffca743602008-10-15 18:38:58 +00001061 E = fproto->arg_type_end(); I && (I != E); ++I)
1062 if (isBlockPointerType(*I)) {
1063 // All the args are checked/rewritten. Don't call twice!
1064 RewriteBlockPointerDecl(D);
1065 break;
1066 }
1067 }
1068}
1069
1070void RewriteBlocks::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
1071 const PointerType *PT = funcType->getAsPointerType();
1072 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +00001073 RewriteFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroffca743602008-10-15 18:38:58 +00001074}
1075
Steve Naroff70f95502008-10-04 17:06:23 +00001076/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1077/// main file of the input.
1078void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1079 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001080 // Since function prototypes don't have ParmDecl's, we check the function
1081 // prototype. This enables us to rewrite function declarations and
1082 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00001083 RewriteFunctionProtoType(FD->getType(), FD);
Sebastian Redld3a413d2009-04-26 20:35:05 +00001084
1085 // FIXME: Handle CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001086 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Naroff70f95502008-10-04 17:06:23 +00001087 CurFunctionDef = FD;
Ted Kremenekeaab2062009-03-12 18:33:24 +00001088 FD->setBody(cast_or_null<CompoundStmt>(RewriteFunctionBody(Body)));
Steve Naroff70f95502008-10-04 17:06:23 +00001089 // This synthesizes and inserts the block "impl" struct, invoke function,
1090 // and any copy/dispose helper functions.
1091 InsertBlockLiteralsWithinFunction(FD);
1092 CurFunctionDef = 0;
1093 }
1094 return;
1095 }
1096 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1097 RewriteMethodDecl(MD);
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001098 if (Stmt *Body = MD->getBody()) {
Steve Naroff70f95502008-10-04 17:06:23 +00001099 CurMethodDef = MD;
1100 RewriteFunctionBody(Body);
1101 InsertBlockLiteralsWithinMethod(MD);
1102 CurMethodDef = 0;
1103 }
1104 }
1105 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1106 if (isBlockPointerType(VD->getType())) {
1107 RewriteBlockPointerDecl(VD);
1108 if (VD->getInit()) {
1109 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001110 RewriteFunctionBody(CBE->getBody());
Steve Naroff70f95502008-10-04 17:06:23 +00001111
1112 // We've just rewritten the block body in place.
1113 // Now we snarf the rewritten text and stash it away for later use.
1114 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1115 RewrittenBlockExprs[CBE] = S;
1116 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1117 // Do the rewrite, using S.size() which contains the rewritten size.
1118 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001119 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00001120 VD->getNameAsCString());
Steve Naroffca743602008-10-15 18:38:58 +00001121 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1122 RewriteCastExpr(CE);
1123 }
1124 }
1125 } else if (VD->getType()->isFunctionPointerType()) {
1126 CheckFunctionPointerDecl(VD->getType(), VD);
1127 if (VD->getInit()) {
1128 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1129 RewriteCastExpr(CE);
Steve Naroff70f95502008-10-04 17:06:23 +00001130 }
1131 }
1132 }
1133 return;
1134 }
1135 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1136 if (isBlockPointerType(TD->getUnderlyingType()))
1137 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001138 else if (TD->getUnderlyingType()->isFunctionPointerType())
1139 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff70f95502008-10-04 17:06:23 +00001140 return;
1141 }
1142 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1143 if (RD->isDefinition()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001144 for (RecordDecl::field_iterator i = RD->field_begin(),
1145 e = RD->field_end(); i != e; ++i) {
Steve Naroff70f95502008-10-04 17:06:23 +00001146 FieldDecl *FD = *i;
1147 if (isBlockPointerType(FD->getType()))
1148 RewriteBlockPointerDecl(FD);
1149 }
1150 }
1151 return;
1152 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001153}