blob: 45c07154106a69864fad76e4895c23965ac6daeb [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
14#include "ASTConsumers.h"
15#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;
40 unsigned MainFileID;
41 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 Naroff13188952008-09-18 14:10:13 +000060 std::string InFileName;
61 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000062
63 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000064public:
Steve Naroff13188952008-09-18 14:10:13 +000065 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
66 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000067 ~RewriteBlocks() {
68 // Get the buffer corresponding to MainFileID.
69 // If we haven't changed it, then we are done.
70 if (const RewriteBuffer *RewriteBuf =
71 Rewrite.getRewriteBufferFor(MainFileID)) {
72 std::string S(RewriteBuf->begin(), RewriteBuf->end());
73 printf("%s\n", S.c_str());
74 } else {
75 printf("No changes\n");
76 }
77 }
78
79 void Initialize(ASTContext &context);
80
81 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
82 void ReplaceText(SourceLocation Start, unsigned OrigLength,
83 const char *NewStr, unsigned NewLength);
84
85 // Top Level Driver code.
86 virtual void HandleTopLevelDecl(Decl *D);
87 void HandleDeclInMainFile(Decl *D);
88
89 // Top level
90 Stmt *RewriteFunctionBody(Stmt *S);
91 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
92 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
93
94 // Block specific rewrite rules.
Steve Naroff70f95502008-10-04 17:06:23 +000095 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000096
97 void RewriteBlockCall(CallExpr *Exp);
98 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff5e52b172008-10-04 18:52:47 +000099 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000100 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
101
Steve Naroff4e13b762008-10-03 20:28:15 +0000102 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
103 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000104 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
105 const char *funcName, std::string Tag);
Steve Naroffacba0f22008-10-04 23:47:37 +0000106 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
107 bool hasCopyDisposeHelpers);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000108 std::string SynthesizeBlockCall(CallExpr *Exp);
109 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
110 const char *FunName);
111
Steve Naroffd3f77902008-10-05 00:06:12 +0000112 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000113 void GetBlockCallExprs(Stmt *S);
Steve Naroffacba0f22008-10-04 23:47:37 +0000114 void GetBlockDeclRefExprs(Stmt *S);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000115
116 // We avoid calling Type::isBlockPointerType(), since it operates on the
117 // canonical type. We only care if the top-level type is a closure pointer.
118 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
119
120 // FIXME: This predicate seems like it would be useful to add to ASTContext.
121 bool isObjCType(QualType T) {
122 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
123 return false;
124
125 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
126
127 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
128 OCT == Context->getCanonicalType(Context->getObjCClassType()))
129 return true;
130
131 if (const PointerType *PT = OCT->getAsPointerType()) {
132 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
133 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
134 return true;
135 }
136 return false;
137 }
138 // ObjC rewrite methods.
139 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
140 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
141 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
142 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffeab5f632008-09-23 19:24:41 +0000143
144 bool BlockPointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000145 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000146};
147
148}
149
150static bool IsHeaderFile(const std::string &Filename) {
151 std::string::size_type DotPos = Filename.rfind('.');
152
153 if (DotPos == std::string::npos) {
154 // no file extension
155 return false;
156 }
157
158 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
159 // C header: .h
160 // C++ header: .hh or .H;
161 return Ext == "h" || Ext == "hh" || Ext == "H";
162}
163
Steve Naroff13188952008-09-18 14:10:13 +0000164RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile,
165 Diagnostic &D, const LangOptions &LOpts) :
166 Diags(D), LangOpts(LOpts) {
167 IsHeader = IsHeaderFile(inFile);
168 InFileName = inFile;
169 OutFileName = outFile;
170 CurFunctionDef = 0;
171 CurMethodDef = 0;
172 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
173 "rewriting failed");
Steve Naroff13188952008-09-18 14:10:13 +0000174}
175
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000176ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
Steve Naroff13188952008-09-18 14:10:13 +0000177 const std::string& OutFile,
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000178 Diagnostic &Diags,
179 const LangOptions &LangOpts) {
Steve Naroff13188952008-09-18 14:10:13 +0000180 return new RewriteBlocks(InFile, OutFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000181}
182
183void RewriteBlocks::Initialize(ASTContext &context) {
184 Context = &context;
185 SM = &Context->getSourceManager();
186
187 // Get the ID and start/end of the main file.
188 MainFileID = SM->getMainFileID();
189 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
190 MainFileStart = MainBuf->getBufferStart();
191 MainFileEnd = MainBuf->getBufferEnd();
192
193 Rewrite.setSourceMgr(Context->getSourceManager());
194
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000195 if (IsHeader)
196 Preamble = "#pragma once\n";
197 Preamble += "#ifndef BLOCK_IMPL\n";
198 Preamble += "#define BLOCK_IMPL\n";
199 Preamble += "struct __block_impl {\n";
200 Preamble += " void *isa;\n";
201 Preamble += " int Flags;\n";
202 Preamble += " int Size;\n";
203 Preamble += " void *FuncPtr;\n";
204 Preamble += "};\n";
205 Preamble += "enum {\n";
206 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
207 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
208 Preamble += "};\n";
209 if (LangOpts.Microsoft)
210 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
211 else
212 Preamble += "#define __OBJC_RW_EXTERN extern\n";
213 Preamble += "// Runtime copy/destroy helper functions\n";
214 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
215 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
216 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
217 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000218 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
219 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000220 Preamble += "#endif\n";
221
222 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
223 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000224}
225
226void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
227 unsigned StrLen)
228{
229 if (!Rewrite.InsertText(Loc, StrData, StrLen))
230 return;
231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232}
233
234void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
237 return;
238 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
239}
240
241void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
242 bool haveBlockPtrs = false;
243 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
244 E = Method->param_end(); I != E; ++I)
245 if (isBlockPointerType((*I)->getType()))
246 haveBlockPtrs = true;
247
248 if (!haveBlockPtrs)
249 return;
250
251 // Do a fuzzy rewrite.
252 // We have 1 or more arguments that have closure pointers.
253 SourceLocation Loc = Method->getLocStart();
254 SourceLocation LocEnd = Method->getLocEnd();
255 const char *startBuf = SM->getCharacterData(Loc);
256 const char *endBuf = SM->getCharacterData(LocEnd);
257
258 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000259 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000260
261 while (*methodPtr++ && (methodPtr != endBuf)) {
262 switch (*methodPtr) {
263 case ':':
264 methodPtr++;
265 if (*methodPtr == '(') {
266 const char *scanType = ++methodPtr;
267 bool foundBlockPointer = false;
268 unsigned parenCount = 1;
269
270 while (parenCount) {
271 switch (*scanType) {
272 case '(':
273 parenCount++;
274 break;
275 case ')':
276 parenCount--;
277 break;
278 case '^':
279 foundBlockPointer = true;
280 break;
281 }
282 scanType++;
283 }
284 if (foundBlockPointer) {
285 // advance the location to startArgList.
286 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
287 assert((Loc.isValid()) && "Invalid Loc");
288 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
289
290 // Advance startBuf. Since the underlying buffer has changed,
291 // it's very important to advance startBuf (so we can correctly
292 // compute a relative Loc the next time around).
293 startBuf = methodPtr;
294 }
295 // Advance the method ptr to the end of the type.
296 methodPtr = scanType;
297 }
298 break;
299 }
300 }
301 return;
302}
303
304void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
305 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
306 E = ClassDecl->instmeth_end(); I != E; ++I)
307 RewriteMethodDecl(*I);
308 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
309 E = ClassDecl->classmeth_end(); I != E; ++I)
310 RewriteMethodDecl(*I);
311}
312
313void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
314 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
315 E = CatDecl->instmeth_end(); I != E; ++I)
316 RewriteMethodDecl(*I);
317 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
318 E = CatDecl->classmeth_end(); I != E; ++I)
319 RewriteMethodDecl(*I);
320}
321
322void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
323 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
324 E = PDecl->instmeth_end(); I != E; ++I)
325 RewriteMethodDecl(*I);
326 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
327 E = PDecl->classmeth_end(); I != E; ++I)
328 RewriteMethodDecl(*I);
329}
330
331//===----------------------------------------------------------------------===//
332// Top Level Driver Code
333//===----------------------------------------------------------------------===//
334
335void RewriteBlocks::HandleTopLevelDecl(Decl *D) {
336 // Two cases: either the decl could be in the main file, or it could be in a
337 // #included file. If the former, rewrite it now. If the later, check to see
338 // if we rewrote the #include/#import.
339 SourceLocation Loc = D->getLocation();
340 Loc = SM->getLogicalLoc(Loc);
341
342 // If this is for a builtin, ignore it.
343 if (Loc.isInvalid()) return;
344
345 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
346 RewriteInterfaceDecl(MD);
347 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
348 RewriteCategoryDecl(CD);
349 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
350 RewriteProtocolDecl(PD);
351
352 // If we have a decl in the main file, see if we should rewrite it.
353 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
354 HandleDeclInMainFile(D);
355 return;
356}
357
358std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
359 const char *funcName,
360 std::string Tag) {
361 const FunctionType *AFT = CE->getFunctionType();
362 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000363 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000364 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000365 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000366
Steve Naroff56ee6892008-10-08 17:01:13 +0000367 BlockDecl *BD = CE->getBlockDecl();
368
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000369 if (isa<FunctionTypeNoProto>(AFT)) {
370 S += "()";
Steve Naroff56ee6892008-10-08 17:01:13 +0000371 } else if (BD->param_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000372 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000373 } else {
374 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
375 assert(FT && "SynthesizeBlockFunc: No function proto");
376 S += '(';
377 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000378 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000379 std::string ParamStr;
Steve Naroff56ee6892008-10-08 17:01:13 +0000380 for (BlockDecl::param_iterator AI = BD->param_begin(),
381 E = BD->param_end(); AI != E; ++AI) {
382 if (AI != BD->param_begin()) S += ", ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000383 ParamStr = (*AI)->getName();
384 (*AI)->getType().getAsStringInternal(ParamStr);
385 S += ParamStr;
386 }
387 if (FT->isVariadic()) {
Steve Naroff56ee6892008-10-08 17:01:13 +0000388 if (!BD->param_empty()) S += ", ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000389 S += "...";
390 }
391 S += ')';
392 }
393 S += " {\n";
394
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000395 // Create local declarations to avoid rewriting all closure decl ref exprs.
396 // First, emit a declaration for all "by ref" decls.
397 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
398 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000399 S += " ";
400 std::string Name = (*I)->getName();
401 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
402 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
403 }
404 // Next, emit a declaration for all "by copy" declarations.
405 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
406 E = BlockByCopyDecls.end(); I != E; ++I) {
407 S += " ";
408 std::string Name = (*I)->getName();
409 // Handle nested closure invocation. For example:
410 //
411 // void (^myImportedClosure)(void);
412 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
413 //
414 // void (^anotherClosure)(void);
415 // anotherClosure = ^(void) {
416 // myImportedClosure(); // import and invoke the closure
417 // };
418 //
419 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000420 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000421 else
422 (*I)->getType().getAsStringInternal(Name);
423 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000424 }
Steve Naroff70f95502008-10-04 17:06:23 +0000425 std::string RewrittenStr = RewrittenBlockExprs[CE];
426 const char *cstr = RewrittenStr.c_str();
427 while (*cstr++ != '{') ;
428 S += cstr;
429 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000430 return S;
431}
432
Steve Naroff4e13b762008-10-03 20:28:15 +0000433std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
434 const char *funcName,
435 std::string Tag) {
436 std::string StructRef = "struct " + Tag;
437 std::string S = "static void __";
438
439 S += funcName;
440 S += "_block_copy_" + utostr(i);
441 S += "(" + StructRef;
442 S += "*dst, " + StructRef;
443 S += "*src) {";
444 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
445 E = ImportedBlockDecls.end(); I != E; ++I) {
446 S += "_Block_copy_assign(&dst->";
447 S += (*I)->getName();
448 S += ", src->";
449 S += (*I)->getName();
450 S += ");}";
451 }
452 S += "\nstatic void __";
453 S += funcName;
454 S += "_block_dispose_" + utostr(i);
455 S += "(" + StructRef;
456 S += "*src) {";
457 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
458 E = ImportedBlockDecls.end(); I != E; ++I) {
459 S += "_Block_destroy(src->";
460 S += (*I)->getName();
461 S += ");";
462 }
463 S += "}\n";
464 return S;
465}
466
Steve Naroffacba0f22008-10-04 23:47:37 +0000467std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
468 bool hasCopyDisposeHelpers) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000469 std::string S = "struct " + Tag;
470 std::string Constructor = " " + Tag;
471
472 S += " {\n struct __block_impl impl;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000473
474 if (hasCopyDisposeHelpers)
475 S += " void *copy;\n void *dispose;\n";
476
Steve Naroff48a8c612008-10-03 12:09:49 +0000477 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000478
Steve Naroffacba0f22008-10-04 23:47:37 +0000479 if (hasCopyDisposeHelpers)
480 Constructor += ", void *copyHelp, void *disposeHelp";
481
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000482 if (BlockDeclRefs.size()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000483 // Output all "by copy" declarations.
484 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
485 E = BlockByCopyDecls.end(); I != E; ++I) {
486 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000487 std::string FieldName = (*I)->getName();
488 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000489 // Handle nested closure invocation. For example:
490 //
491 // void (^myImportedBlock)(void);
492 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
493 //
494 // void (^anotherBlock)(void);
495 // anotherBlock = ^(void) {
496 // myImportedBlock(); // import and invoke the closure
497 // };
498 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000499 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000500 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000501 Constructor += ", void *" + ArgName;
502 } else {
503 (*I)->getType().getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000504 (*I)->getType().getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000505 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000506 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000507 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000508 }
509 // Output all "by ref" declarations.
510 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
511 E = BlockByRefDecls.end(); I != E; ++I) {
512 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000513 std::string FieldName = (*I)->getName();
514 std::string ArgName = "_" + FieldName;
515 // Handle nested closure invocation. For example:
516 //
517 // void (^myImportedBlock)(void);
518 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
519 //
520 // void (^anotherBlock)(void);
521 // anotherBlock = ^(void) {
522 // myImportedBlock(); // import and invoke the closure
523 // };
524 //
525 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000526 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000527 Constructor += ", void *" + ArgName;
528 } else {
529 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000530 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000531 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000532 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000533 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000534 }
535 // Finish writing the constructor.
536 // FIXME: handle NSConcreteGlobalBlock.
537 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000538 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000539 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
540
Steve Naroffacba0f22008-10-04 23:47:37 +0000541 if (hasCopyDisposeHelpers)
542 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
543
Steve Naroff48a8c612008-10-03 12:09:49 +0000544 // Initialize all "by copy" arguments.
545 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
546 E = BlockByCopyDecls.end(); I != E; ++I) {
547 std::string Name = (*I)->getName();
548 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000549 if (isBlockPointerType((*I)->getType()))
550 Constructor += Name + " = (struct __block_impl *)_";
551 else
552 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000553 Constructor += Name + ";\n";
554 }
555 // Initialize all "by ref" arguments.
556 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
557 E = BlockByRefDecls.end(); I != E; ++I) {
558 std::string Name = (*I)->getName();
559 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000560 if (isBlockPointerType((*I)->getType()))
561 Constructor += Name + " = (struct __block_impl *)_";
562 else
563 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000564 Constructor += Name + ";\n";
565 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000566 } else {
567 // Finish writing the constructor.
568 // FIXME: handle NSConcreteGlobalBlock.
569 Constructor += ", int flags=0) {\n";
570 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
571 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000572 if (hasCopyDisposeHelpers)
573 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000574 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000575 Constructor += " ";
576 Constructor += "}\n";
577 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000578 S += "};\n";
579 return S;
580}
581
582void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
583 const char *FunName) {
584 // Insert closures that were part of the function.
585 for (unsigned i = 0; i < Blocks.size(); i++) {
Steve Naroffacba0f22008-10-04 23:47:37 +0000586
Steve Naroffd3f77902008-10-05 00:06:12 +0000587 CollectBlockDeclRefInfo(Blocks[i]);
588
Steve Naroff48a8c612008-10-03 12:09:49 +0000589 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000590
Steve Naroffacba0f22008-10-04 23:47:37 +0000591 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
592 ImportedBlockDecls.size() > 0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000593
594 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000595
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000596 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
597
598 InsertText(FunLocStart, CF.c_str(), CF.size());
599
Steve Naroff4e13b762008-10-03 20:28:15 +0000600 if (ImportedBlockDecls.size()) {
601 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
602 InsertText(FunLocStart, HF.c_str(), HF.size());
603 }
604
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000605 BlockDeclRefs.clear();
606 BlockByRefDecls.clear();
607 BlockByCopyDecls.clear();
608 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000609 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000610 }
611 Blocks.clear();
Steve Naroff8e9216d2008-10-04 17:10:02 +0000612 RewrittenBlockExprs.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000613}
614
615void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000616 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000617 const char *FuncName = FD->getName();
618
619 SynthesizeBlockLiterals(FunLocStart, FuncName);
620}
621
622void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
623 SourceLocation FunLocStart = MD->getLocStart();
624 std::string FuncName = std::string(MD->getSelector().getName());
625 // Convert colons to underscores.
626 std::string::size_type loc = 0;
627 while ((loc = FuncName.find(":", loc)) != std::string::npos)
628 FuncName.replace(loc, 1, "_");
629
630 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
631}
632
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000633
634void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
635 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
636 CI != E; ++CI)
637 if (*CI)
638 GetBlockDeclRefExprs(*CI);
639
640 // Handle specific things.
641 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
642 // FIXME: Handle enums.
643 if (!isa<FunctionDecl>(CDRE->getDecl()))
644 BlockDeclRefs.push_back(CDRE);
645 return;
646}
647
648void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
649 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
650 CI != E; ++CI)
651 if (*CI)
652 GetBlockCallExprs(*CI);
653
654 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000655 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000656 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000657 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000658 }
659 return;
660}
661
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000662std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
663 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000664 const char *closureName = 0;
665 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000666
667 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
668 closureName = DRE->getDecl()->getName();
669 CPT = DRE->getType()->getAsBlockPointerType();
670 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
671 closureName = CDRE->getDecl()->getName();
672 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000673 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
674 closureName = MExpr->getMemberDecl()->getName();
675 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000676 } else {
677 assert(1 && "RewriteBlockClass: Bad type");
678 }
679 assert(CPT && "RewriteBlockClass: Bad type");
680 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
681 assert(FT && "RewriteBlockClass: Bad type");
682 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
683 // FTP will be null for closures that don't take arguments.
684
685 // Build a closure call - start with a paren expr to enforce precedence.
686 std::string BlockCall = "(";
687
688 // Synthesize the cast.
689 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000690 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000691 if (FTP) {
692 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
693 E = FTP->arg_type_end(); I && (I != E); ++I)
694 BlockCall += ", " + (*I).getAsString();
695 }
696 BlockCall += "))"; // close the argument list and paren expression.
697
Steve Naroff83ba14e2008-10-03 15:04:50 +0000698 // Invoke the closure. We need to cast it since the declaration type is
699 // bogus (it's a function pointer type)
700 BlockCall += "((struct __block_impl *)";
701 std::string closureExprBufStr;
702 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
703 Exp->getCallee()->printPretty(closureExprBuf);
704 BlockCall += closureExprBuf.str();
705 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000706
707 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000708 BlockCall += "((struct __block_impl *)";
Steve Naroffb65a4f12008-10-04 17:45:51 +0000709 BlockCall += closureExprBuf.str();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000710 for (CallExpr::arg_iterator I = Exp->arg_begin(),
711 E = Exp->arg_end(); I != E; ++I) {
712 std::string syncExprBufS;
713 llvm::raw_string_ostream Buf(syncExprBufS);
714 (*I)->printPretty(Buf);
715 BlockCall += ", " + Buf.str();
716 }
717 return BlockCall;
718}
719
720void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
721 std::string BlockCall = SynthesizeBlockCall(Exp);
722
723 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
724 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
725
726 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
727 BlockCall.c_str(), BlockCall.size());
728}
729
Steve Naroff5e52b172008-10-04 18:52:47 +0000730void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
731 // FIXME: Add more elaborate code generation required by the ABI.
732 InsertText(BDRE->getLocStart(), "*", 1);
733}
734
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000735void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
736 SourceLocation DeclLoc = FD->getLocation();
737 unsigned parenCount = 0, nArgs = 0;
738
739 // We have 1 or more arguments that have closure pointers.
740 const char *startBuf = SM->getCharacterData(DeclLoc);
741 const char *startArgList = strchr(startBuf, '(');
742
743 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
744
745 parenCount++;
746 // advance the location to startArgList.
747 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1);
748 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
749
750 const char *topLevelCommaCursor = 0;
751 const char *argPtr = startArgList;
752 bool scannedBlockDecl = false;
Steve Naroff8af6a452008-10-02 17:12:56 +0000753 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000754
755 while (*argPtr++ && parenCount) {
756 switch (*argPtr) {
757 case '^':
758 scannedBlockDecl = true;
759 break;
760 case '(':
761 parenCount++;
762 break;
763 case ')':
764 parenCount--;
765 if (parenCount == 0) {
766 if (scannedBlockDecl) {
767 // If we are rewriting a definition, don't forget the arg name.
768 if (FD->getBody())
769 Tag += FD->getParamDecl(nArgs)->getName();
770 // The last argument is a closure pointer decl, rewrite it!
771 if (topLevelCommaCursor)
772 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size());
773 else
774 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
775 scannedBlockDecl = false; // reset.
776 }
777 nArgs++;
778 }
779 break;
780 case ',':
781 if (parenCount == 1) {
782 // Make sure the function takes more than one argument.
783 assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused");
784 if (scannedBlockDecl) {
785 // If we are rewriting a definition, don't forget the arg name.
786 if (FD->getBody())
787 Tag += FD->getParamDecl(nArgs)->getName();
788 // The current argument is a closure pointer decl, rewrite it!
789 if (topLevelCommaCursor)
790 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size());
791 else
792 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
793 scannedBlockDecl = false;
794 }
795 nArgs++;
796 // advance the location to topLevelCommaCursor.
797 if (topLevelCommaCursor)
798 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor);
799 else
800 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1);
801 topLevelCommaCursor = argPtr;
802 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
803 }
804 break;
805 }
806 }
807 return;
808}
809
Steve Naroffeab5f632008-09-23 19:24:41 +0000810bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) {
811 const BlockPointerType *BPT = QT->getAsBlockPointerType();
812 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
813 const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
814 if (FTP) {
815 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
816 E = FTP->arg_type_end(); I != E; ++I)
817 if (isBlockPointerType(*I))
818 return true;
819 }
820 return false;
821}
822
823void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000824 const char *&LParen, const char *&RParen) {
825 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000826 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
827
828 LParen = argPtr; // output the start.
829 argPtr++; // skip past the left paren.
830 unsigned parenCount = 1;
831
832 while (*argPtr && parenCount) {
833 switch (*argPtr) {
834 case '(': parenCount++; break;
835 case ')': parenCount--; break;
836 default: break;
837 }
838 if (parenCount) argPtr++;
839 }
840 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
841 RParen = argPtr; // output the end
842}
843
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000844void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000845 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
846 RewriteBlockPointerFunctionArgs(FD);
847 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000848 }
849 // Handle Variables and Typedefs.
850 SourceLocation DeclLoc = ND->getLocation();
851 QualType DeclT;
852 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
853 DeclT = VD->getType();
854 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
855 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000856 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
857 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000858 else
859 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000860
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000861 const char *startBuf = SM->getCharacterData(DeclLoc);
862 const char *endBuf = startBuf;
863 // scan backward (from the decl location) for the end of the previous decl.
864 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
865 startBuf--;
866 assert((*startBuf == '^') &&
867 "RewriteBlockPointerDecl() scan error: no caret");
868 // Replace the '^' with '*', computing a negative offset.
869 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
870 ReplaceText(DeclLoc, 1, "*", 1);
871
872 if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) {
873 // Replace the '^' with '*' for arguments.
874 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000875 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000876 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000877 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
878 while (argListBegin < argListEnd) {
879 if (*argListBegin == '^') {
880 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
881 ReplaceText(CaretLoc, 1, "*", 1);
882 }
883 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000884 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000885 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000886 return;
887}
888
Steve Naroffd3f77902008-10-05 00:06:12 +0000889void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000890 // Add initializers for any closure decl refs.
891 GetBlockDeclRefExprs(Exp);
892 if (BlockDeclRefs.size()) {
893 // Unique all "by copy" declarations.
894 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
895 if (!BlockDeclRefs[i]->isByRef())
896 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
897 // Unique all "by ref" declarations.
898 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
899 if (BlockDeclRefs[i]->isByRef()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000900 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
901 }
Steve Naroffacba0f22008-10-04 23:47:37 +0000902 // Find any imported blocks...they will need special attention.
903 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
904 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
905 GetBlockCallExprs(Blocks[i]);
906 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
907 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000908 }
Steve Naroffd3f77902008-10-05 00:06:12 +0000909}
910
911std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
912 Blocks.push_back(Exp);
913
914 CollectBlockDeclRefInfo(Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000915 std::string FuncName;
916
917 if (CurFunctionDef)
918 FuncName = std::string(CurFunctionDef->getName());
919 else if (CurMethodDef) {
920 FuncName = std::string(CurMethodDef->getSelector().getName());
921 // Convert colons to underscores.
922 std::string::size_type loc = 0;
923 while ((loc = FuncName.find(":", loc)) != std::string::npos)
924 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000925 } else if (VD)
926 FuncName = std::string(VD->getName());
927
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000928 std::string BlockNumber = utostr(Blocks.size()-1);
929
Steve Naroff83ba14e2008-10-03 15:04:50 +0000930 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000931 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000932
Steve Naroff83ba14e2008-10-03 15:04:50 +0000933 std::string FunkTypeStr;
934
935 // Get a pointer to the function type so we can cast appropriately.
936 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
937
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000938 // Rewrite the closure block with a compound literal. The first cast is
939 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000940 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000941
Steve Naroff83ba14e2008-10-03 15:04:50 +0000942 Init += ")&" + Tag;
943
944 // Initialize the block function.
945 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000946
Steve Naroffacba0f22008-10-04 23:47:37 +0000947 if (ImportedBlockDecls.size()) {
948 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
949 Init += ",(void*)" + Buf;
950 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
951 Init += ",(void*)" + Buf;
952 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000953 // Add initializers for any closure decl refs.
954 if (BlockDeclRefs.size()) {
955 // Output all "by copy" declarations.
956 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
957 E = BlockByCopyDecls.end(); I != E; ++I) {
958 Init += ",";
959 if (isObjCType((*I)->getType())) {
960 Init += "[[";
961 Init += (*I)->getName();
962 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000963 } else if (isBlockPointerType((*I)->getType())) {
964 Init += "(void *)";
965 Init += (*I)->getName();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000966 } else {
967 Init += (*I)->getName();
968 }
969 }
970 // Output all "by ref" declarations.
971 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
972 E = BlockByRefDecls.end(); I != E; ++I) {
973 Init += ",&";
974 Init += (*I)->getName();
975 }
976 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000977 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000978 BlockDeclRefs.clear();
979 BlockByRefDecls.clear();
980 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000981 ImportedBlockDecls.clear();
982
Steve Naroff70f95502008-10-04 17:06:23 +0000983 return Init;
984}
985
986//===----------------------------------------------------------------------===//
987// Function Body / Expression rewriting
988//===----------------------------------------------------------------------===//
989
990Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
991 // Start by rewriting all children.
992 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
993 CI != E; ++CI)
994 if (*CI) {
995 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
996 Stmt *newStmt = RewriteFunctionBody(*CI);
997 if (newStmt)
998 *CI = newStmt;
999
1000 // We've just rewritten the block body in place.
1001 // Now we snarf the rewritten text and stash it away for later use.
1002 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1003 RewrittenBlockExprs[CBE] = S;
1004 std::string Init = SynthesizeBlockInitExpr(CBE);
1005 // Do the rewrite, using S.size() which contains the rewritten size.
1006 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1007 } else {
1008 Stmt *newStmt = RewriteFunctionBody(*CI);
1009 if (newStmt)
1010 *CI = newStmt;
1011 }
1012 }
1013 // Handle specific things.
1014 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1015 if (CE->getCallee()->getType()->isBlockPointerType())
1016 RewriteBlockCall(CE);
1017 }
1018 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001019 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1020 DI != DE; ++DI) {
1021
1022 ScopedDecl *SD = *DI;
1023 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1024 if (isBlockPointerType(ND->getType()))
1025 RewriteBlockPointerDecl(ND);
1026 }
1027 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1028 if (isBlockPointerType(TD->getUnderlyingType()))
1029 RewriteBlockPointerDecl(TD);
1030 }
Steve Naroff70f95502008-10-04 17:06:23 +00001031 }
1032 }
Steve Naroff5e52b172008-10-04 18:52:47 +00001033 // Handle specific things.
1034 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1035 if (BDRE->isByRef())
1036 RewriteBlockDeclRefExpr(BDRE);
1037 }
Steve Naroff70f95502008-10-04 17:06:23 +00001038 // Return this stmt unmodified.
1039 return S;
1040}
1041
1042/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1043/// main file of the input.
1044void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1045 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1046
1047 // Since function prototypes don't have ParmDecl's, we check the function
1048 // prototype. This enables us to rewrite function declarations and
1049 // definitions using the same code.
1050 QualType funcType = FD->getType();
1051
1052 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
1053 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
1054 E = fproto->arg_type_end(); I && (I != E); ++I)
1055 if (isBlockPointerType(*I)) {
1056 // All the args are checked/rewritten. Don't call twice!
1057 RewriteBlockPointerDecl(FD);
1058 break;
1059 }
1060 }
1061 if (Stmt *Body = FD->getBody()) {
1062 CurFunctionDef = FD;
1063 FD->setBody(RewriteFunctionBody(Body));
1064 // This synthesizes and inserts the block "impl" struct, invoke function,
1065 // and any copy/dispose helper functions.
1066 InsertBlockLiteralsWithinFunction(FD);
1067 CurFunctionDef = 0;
1068 }
1069 return;
1070 }
1071 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1072 RewriteMethodDecl(MD);
1073 if (Stmt *Body = MD->getBody()) {
1074 CurMethodDef = MD;
1075 RewriteFunctionBody(Body);
1076 InsertBlockLiteralsWithinMethod(MD);
1077 CurMethodDef = 0;
1078 }
1079 }
1080 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1081 if (isBlockPointerType(VD->getType())) {
1082 RewriteBlockPointerDecl(VD);
1083 if (VD->getInit()) {
1084 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
1085 RewriteFunctionBody(VD->getInit());
1086
1087 // We've just rewritten the block body in place.
1088 // Now we snarf the rewritten text and stash it away for later use.
1089 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1090 RewrittenBlockExprs[CBE] = S;
1091 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1092 // Do the rewrite, using S.size() which contains the rewritten size.
1093 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1094 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
1095 }
1096 }
1097 }
1098 return;
1099 }
1100 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1101 if (isBlockPointerType(TD->getUnderlyingType()))
1102 RewriteBlockPointerDecl(TD);
1103 return;
1104 }
1105 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1106 if (RD->isDefinition()) {
1107 for (RecordDecl::field_const_iterator i = RD->field_begin(),
1108 e = RD->field_end(); i != e; ++i) {
1109 FieldDecl *FD = *i;
1110 if (isBlockPointerType(FD->getType()))
1111 RewriteBlockPointerDecl(FD);
1112 }
1113 }
1114 return;
1115 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001116}