blob: 9bced9602b22ef74eb4a58cc1e17f8d085cc7ecf [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;
37 unsigned NoNestedBlockCalls;
38
39 ASTContext *Context;
40 SourceManager *SM;
41 unsigned MainFileID;
42 const char *MainFileStart, *MainFileEnd;
43
44 // Block expressions.
45 llvm::SmallVector<BlockExpr *, 32> Blocks;
46 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
47 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
48
49 // Block related declarations.
50 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
51 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Steve Naroff4e13b762008-10-03 20:28:15 +000052 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Steve Naroff70f95502008-10-04 17:06:23 +000053
54 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000055
56 // The function/method we are rewriting.
57 FunctionDecl *CurFunctionDef;
58 ObjCMethodDecl *CurMethodDef;
59
60 bool IsHeader;
Steve Naroff13188952008-09-18 14:10:13 +000061 std::string InFileName;
62 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000063
64 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000065public:
Steve Naroff13188952008-09-18 14:10:13 +000066 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
67 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000068 ~RewriteBlocks() {
69 // Get the buffer corresponding to MainFileID.
70 // If we haven't changed it, then we are done.
71 if (const RewriteBuffer *RewriteBuf =
72 Rewrite.getRewriteBufferFor(MainFileID)) {
73 std::string S(RewriteBuf->begin(), RewriteBuf->end());
74 printf("%s\n", S.c_str());
75 } else {
76 printf("No changes\n");
77 }
78 }
79
80 void Initialize(ASTContext &context);
81
82 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
83 void ReplaceText(SourceLocation Start, unsigned OrigLength,
84 const char *NewStr, unsigned NewLength);
85
86 // Top Level Driver code.
87 virtual void HandleTopLevelDecl(Decl *D);
88 void HandleDeclInMainFile(Decl *D);
89
90 // Top level
91 Stmt *RewriteFunctionBody(Stmt *S);
92 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
93 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
94
95 // Block specific rewrite rules.
Steve Naroff70f95502008-10-04 17:06:23 +000096 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000097
98 void RewriteBlockCall(CallExpr *Exp);
99 void RewriteBlockPointerDecl(NamedDecl *VD);
100 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);
106 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag);
107 std::string SynthesizeBlockCall(CallExpr *Exp);
108 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
109 const char *FunName);
110
111 void GetBlockDeclRefExprs(Stmt *S);
112 void GetBlockCallExprs(Stmt *S);
113
114 // We avoid calling Type::isBlockPointerType(), since it operates on the
115 // canonical type. We only care if the top-level type is a closure pointer.
116 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
117
118 // FIXME: This predicate seems like it would be useful to add to ASTContext.
119 bool isObjCType(QualType T) {
120 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
121 return false;
122
123 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
124
125 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
126 OCT == Context->getCanonicalType(Context->getObjCClassType()))
127 return true;
128
129 if (const PointerType *PT = OCT->getAsPointerType()) {
130 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
131 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
132 return true;
133 }
134 return false;
135 }
136 // ObjC rewrite methods.
137 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
138 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
139 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
140 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffeab5f632008-09-23 19:24:41 +0000141
142 bool BlockPointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000143 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000144};
145
146}
147
148static bool IsHeaderFile(const std::string &Filename) {
149 std::string::size_type DotPos = Filename.rfind('.');
150
151 if (DotPos == std::string::npos) {
152 // no file extension
153 return false;
154 }
155
156 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
157 // C header: .h
158 // C++ header: .hh or .H;
159 return Ext == "h" || Ext == "hh" || Ext == "H";
160}
161
Steve Naroff13188952008-09-18 14:10:13 +0000162RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile,
163 Diagnostic &D, const LangOptions &LOpts) :
164 Diags(D), LangOpts(LOpts) {
165 IsHeader = IsHeaderFile(inFile);
166 InFileName = inFile;
167 OutFileName = outFile;
168 CurFunctionDef = 0;
169 CurMethodDef = 0;
170 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
171 "rewriting failed");
172 NoNestedBlockCalls = Diags.getCustomDiagID(Diagnostic::Warning,
173 "Rewrite support for closure calls nested within closure blocks is incomplete");
174}
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
367 if (isa<FunctionTypeNoProto>(AFT)) {
368 S += "()";
369 } else if (CE->arg_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000370 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000371 } else {
372 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
373 assert(FT && "SynthesizeBlockFunc: No function proto");
374 S += '(';
375 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000376 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000377 std::string ParamStr;
Steve Naroff9c3c9022008-09-17 18:37:59 +0000378 for (BlockExpr::arg_iterator AI = CE->arg_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000379 E = CE->arg_end(); AI != E; ++AI) {
380 if (AI != CE->arg_begin()) S += ", ";
381 ParamStr = (*AI)->getName();
382 (*AI)->getType().getAsStringInternal(ParamStr);
383 S += ParamStr;
384 }
385 if (FT->isVariadic()) {
386 if (!CE->arg_empty()) S += ", ";
387 S += "...";
388 }
389 S += ')';
390 }
391 S += " {\n";
392
393 bool haveByRefDecls = false;
394
395 // 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) {
399 // Note: It is not possible to have "by ref" closure pointer decls.
400 haveByRefDecls = true;
401 S += " ";
402 std::string Name = (*I)->getName();
403 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
404 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
405 }
406 // Next, emit a declaration for all "by copy" declarations.
407 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
408 E = BlockByCopyDecls.end(); I != E; ++I) {
409 S += " ";
410 std::string Name = (*I)->getName();
411 // Handle nested closure invocation. For example:
412 //
413 // void (^myImportedClosure)(void);
414 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
415 //
416 // void (^anotherClosure)(void);
417 // anotherClosure = ^(void) {
418 // myImportedClosure(); // import and invoke the closure
419 // };
420 //
421 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000422 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000423 else
424 (*I)->getType().getAsStringInternal(Name);
425 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000426 }
Steve Naroff70f95502008-10-04 17:06:23 +0000427 std::string RewrittenStr = RewrittenBlockExprs[CE];
428 const char *cstr = RewrittenStr.c_str();
429 while (*cstr++ != '{') ;
430 S += cstr;
431 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000432 return S;
433}
434
Steve Naroff4e13b762008-10-03 20:28:15 +0000435std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
436 const char *funcName,
437 std::string Tag) {
438 std::string StructRef = "struct " + Tag;
439 std::string S = "static void __";
440
441 S += funcName;
442 S += "_block_copy_" + utostr(i);
443 S += "(" + StructRef;
444 S += "*dst, " + StructRef;
445 S += "*src) {";
446 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
447 E = ImportedBlockDecls.end(); I != E; ++I) {
448 S += "_Block_copy_assign(&dst->";
449 S += (*I)->getName();
450 S += ", src->";
451 S += (*I)->getName();
452 S += ");}";
453 }
454 S += "\nstatic void __";
455 S += funcName;
456 S += "_block_dispose_" + utostr(i);
457 S += "(" + StructRef;
458 S += "*src) {";
459 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
460 E = ImportedBlockDecls.end(); I != E; ++I) {
461 S += "_Block_destroy(src->";
462 S += (*I)->getName();
463 S += ");";
464 }
465 S += "}\n";
466 return S;
467}
468
Steve Naroff48a8c612008-10-03 12:09:49 +0000469std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag) {
470 std::string S = "struct " + Tag;
471 std::string Constructor = " " + Tag;
472
473 S += " {\n struct __block_impl impl;\n";
474 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000475
476 GetBlockDeclRefExprs(CE);
477 if (BlockDeclRefs.size()) {
478 // Unique all "by copy" declarations.
479 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
480 if (!BlockDeclRefs[i]->isByRef())
481 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
482 // Unique all "by ref" declarations.
483 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
484 if (BlockDeclRefs[i]->isByRef())
485 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
486
487 // Output all "by copy" declarations.
488 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
489 E = BlockByCopyDecls.end(); I != E; ++I) {
490 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000491 std::string FieldName = (*I)->getName();
492 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000493 // Handle nested closure invocation. For example:
494 //
495 // void (^myImportedBlock)(void);
496 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
497 //
498 // void (^anotherBlock)(void);
499 // anotherBlock = ^(void) {
500 // myImportedBlock(); // import and invoke the closure
501 // };
502 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000503 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000504 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000505 Constructor += ", void *" + ArgName;
506 } else {
507 (*I)->getType().getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000508 (*I)->getType().getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000509 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000510 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000511 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000512 }
513 // Output all "by ref" declarations.
514 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
515 E = BlockByRefDecls.end(); I != E; ++I) {
516 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000517 std::string FieldName = (*I)->getName();
518 std::string ArgName = "_" + FieldName;
519 // Handle nested closure invocation. For example:
520 //
521 // void (^myImportedBlock)(void);
522 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
523 //
524 // void (^anotherBlock)(void);
525 // anotherBlock = ^(void) {
526 // myImportedBlock(); // import and invoke the closure
527 // };
528 //
529 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000530 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000531 Constructor += ", void *" + ArgName;
532 } else {
533 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000534 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000535 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000536 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000537 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000538 }
539 // Finish writing the constructor.
540 // FIXME: handle NSConcreteGlobalBlock.
541 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000542 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000543 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
544
545 // Initialize all "by copy" arguments.
546 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
547 E = BlockByCopyDecls.end(); I != E; ++I) {
548 std::string Name = (*I)->getName();
549 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000550 if (isBlockPointerType((*I)->getType()))
551 Constructor += Name + " = (struct __block_impl *)_";
552 else
553 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000554 Constructor += Name + ";\n";
555 }
556 // Initialize all "by ref" arguments.
557 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
558 E = BlockByRefDecls.end(); I != E; ++I) {
559 std::string Name = (*I)->getName();
560 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 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000567 } else {
568 // Finish writing the constructor.
569 // FIXME: handle NSConcreteGlobalBlock.
570 Constructor += ", int flags=0) {\n";
571 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
572 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000573 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000574 Constructor += " ";
575 Constructor += "}\n";
576 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000577 S += "};\n";
578 return S;
579}
580
581void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
582 const char *FunName) {
583 // Insert closures that were part of the function.
584 for (unsigned i = 0; i < Blocks.size(); i++) {
585
Steve Naroff48a8c612008-10-03 12:09:49 +0000586 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000587
588 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag);
589
590 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000591
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000592 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
593
594 InsertText(FunLocStart, CF.c_str(), CF.size());
595
Steve Naroff4e13b762008-10-03 20:28:15 +0000596 if (ImportedBlockDecls.size()) {
597 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
598 InsertText(FunLocStart, HF.c_str(), HF.size());
599 }
600
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000601 BlockDeclRefs.clear();
602 BlockByRefDecls.clear();
603 BlockByCopyDecls.clear();
604 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000605 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000606 }
607 Blocks.clear();
608}
609
610void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000611 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000612 const char *FuncName = FD->getName();
613
614 SynthesizeBlockLiterals(FunLocStart, FuncName);
615}
616
617void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
618 SourceLocation FunLocStart = MD->getLocStart();
619 std::string FuncName = std::string(MD->getSelector().getName());
620 // Convert colons to underscores.
621 std::string::size_type loc = 0;
622 while ((loc = FuncName.find(":", loc)) != std::string::npos)
623 FuncName.replace(loc, 1, "_");
624
625 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
626}
627
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000628
629void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
630 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
631 CI != E; ++CI)
632 if (*CI)
633 GetBlockDeclRefExprs(*CI);
634
635 // Handle specific things.
636 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
637 // FIXME: Handle enums.
638 if (!isa<FunctionDecl>(CDRE->getDecl()))
639 BlockDeclRefs.push_back(CDRE);
640 return;
641}
642
643void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
644 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
645 CI != E; ++CI)
646 if (*CI)
647 GetBlockCallExprs(*CI);
648
649 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000650 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000651 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000652 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000653 }
654 return;
655}
656
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000657std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
658 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000659 const char *closureName = 0;
660 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000661
662 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
663 closureName = DRE->getDecl()->getName();
664 CPT = DRE->getType()->getAsBlockPointerType();
665 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
666 closureName = CDRE->getDecl()->getName();
667 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000668 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
669 closureName = MExpr->getMemberDecl()->getName();
670 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000671 } else {
672 assert(1 && "RewriteBlockClass: Bad type");
673 }
674 assert(CPT && "RewriteBlockClass: Bad type");
675 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
676 assert(FT && "RewriteBlockClass: Bad type");
677 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
678 // FTP will be null for closures that don't take arguments.
679
680 // Build a closure call - start with a paren expr to enforce precedence.
681 std::string BlockCall = "(";
682
683 // Synthesize the cast.
684 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000685 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000686 if (FTP) {
687 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
688 E = FTP->arg_type_end(); I && (I != E); ++I)
689 BlockCall += ", " + (*I).getAsString();
690 }
691 BlockCall += "))"; // close the argument list and paren expression.
692
Steve Naroff83ba14e2008-10-03 15:04:50 +0000693 // Invoke the closure. We need to cast it since the declaration type is
694 // bogus (it's a function pointer type)
695 BlockCall += "((struct __block_impl *)";
696 std::string closureExprBufStr;
697 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
698 Exp->getCallee()->printPretty(closureExprBuf);
699 BlockCall += closureExprBuf.str();
700 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000701
702 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000703 BlockCall += "((struct __block_impl *)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000704 BlockCall += closureName;
705 for (CallExpr::arg_iterator I = Exp->arg_begin(),
706 E = Exp->arg_end(); I != E; ++I) {
707 std::string syncExprBufS;
708 llvm::raw_string_ostream Buf(syncExprBufS);
709 (*I)->printPretty(Buf);
710 BlockCall += ", " + Buf.str();
711 }
712 return BlockCall;
713}
714
715void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
716 std::string BlockCall = SynthesizeBlockCall(Exp);
717
718 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
719 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
720
721 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
722 BlockCall.c_str(), BlockCall.size());
723}
724
725void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
726 SourceLocation DeclLoc = FD->getLocation();
727 unsigned parenCount = 0, nArgs = 0;
728
729 // We have 1 or more arguments that have closure pointers.
730 const char *startBuf = SM->getCharacterData(DeclLoc);
731 const char *startArgList = strchr(startBuf, '(');
732
733 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
734
735 parenCount++;
736 // advance the location to startArgList.
737 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1);
738 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
739
740 const char *topLevelCommaCursor = 0;
741 const char *argPtr = startArgList;
742 bool scannedBlockDecl = false;
Steve Naroff8af6a452008-10-02 17:12:56 +0000743 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000744
745 while (*argPtr++ && parenCount) {
746 switch (*argPtr) {
747 case '^':
748 scannedBlockDecl = true;
749 break;
750 case '(':
751 parenCount++;
752 break;
753 case ')':
754 parenCount--;
755 if (parenCount == 0) {
756 if (scannedBlockDecl) {
757 // If we are rewriting a definition, don't forget the arg name.
758 if (FD->getBody())
759 Tag += FD->getParamDecl(nArgs)->getName();
760 // The last argument is a closure pointer decl, rewrite it!
761 if (topLevelCommaCursor)
762 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size());
763 else
764 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
765 scannedBlockDecl = false; // reset.
766 }
767 nArgs++;
768 }
769 break;
770 case ',':
771 if (parenCount == 1) {
772 // Make sure the function takes more than one argument.
773 assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused");
774 if (scannedBlockDecl) {
775 // If we are rewriting a definition, don't forget the arg name.
776 if (FD->getBody())
777 Tag += FD->getParamDecl(nArgs)->getName();
778 // The current argument is a closure pointer decl, rewrite it!
779 if (topLevelCommaCursor)
780 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size());
781 else
782 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
783 scannedBlockDecl = false;
784 }
785 nArgs++;
786 // advance the location to topLevelCommaCursor.
787 if (topLevelCommaCursor)
788 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor);
789 else
790 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1);
791 topLevelCommaCursor = argPtr;
792 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
793 }
794 break;
795 }
796 }
797 return;
798}
799
Steve Naroffeab5f632008-09-23 19:24:41 +0000800bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) {
801 const BlockPointerType *BPT = QT->getAsBlockPointerType();
802 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
803 const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
804 if (FTP) {
805 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
806 E = FTP->arg_type_end(); I != E; ++I)
807 if (isBlockPointerType(*I))
808 return true;
809 }
810 return false;
811}
812
813void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000814 const char *&LParen, const char *&RParen) {
815 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000816 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
817
818 LParen = argPtr; // output the start.
819 argPtr++; // skip past the left paren.
820 unsigned parenCount = 1;
821
822 while (*argPtr && parenCount) {
823 switch (*argPtr) {
824 case '(': parenCount++; break;
825 case ')': parenCount--; break;
826 default: break;
827 }
828 if (parenCount) argPtr++;
829 }
830 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
831 RParen = argPtr; // output the end
832}
833
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000834void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000835 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
836 RewriteBlockPointerFunctionArgs(FD);
837 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000838 }
839 // Handle Variables and Typedefs.
840 SourceLocation DeclLoc = ND->getLocation();
841 QualType DeclT;
842 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
843 DeclT = VD->getType();
844 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
845 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000846 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
847 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000848 else
849 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000850
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000851 const char *startBuf = SM->getCharacterData(DeclLoc);
852 const char *endBuf = startBuf;
853 // scan backward (from the decl location) for the end of the previous decl.
854 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
855 startBuf--;
856 assert((*startBuf == '^') &&
857 "RewriteBlockPointerDecl() scan error: no caret");
858 // Replace the '^' with '*', computing a negative offset.
859 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
860 ReplaceText(DeclLoc, 1, "*", 1);
861
862 if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) {
863 // Replace the '^' with '*' for arguments.
864 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000865 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000866 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000867 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
868 while (argListBegin < argListEnd) {
869 if (*argListBegin == '^') {
870 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
871 ReplaceText(CaretLoc, 1, "*", 1);
872 }
873 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000874 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000875 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000876 return;
877}
878
Steve Naroff70f95502008-10-04 17:06:23 +0000879std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000880 Blocks.push_back(Exp);
881 bool haveByRefDecls = false;
882
883 // Add initializers for any closure decl refs.
884 GetBlockDeclRefExprs(Exp);
885 if (BlockDeclRefs.size()) {
886 // Unique all "by copy" declarations.
887 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
888 if (!BlockDeclRefs[i]->isByRef())
889 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
890 // Unique all "by ref" declarations.
891 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
892 if (BlockDeclRefs[i]->isByRef()) {
893 haveByRefDecls = true;
894 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
895 }
896 }
897 std::string FuncName;
898
899 if (CurFunctionDef)
900 FuncName = std::string(CurFunctionDef->getName());
901 else if (CurMethodDef) {
902 FuncName = std::string(CurMethodDef->getSelector().getName());
903 // Convert colons to underscores.
904 std::string::size_type loc = 0;
905 while ((loc = FuncName.find(":", loc)) != std::string::npos)
906 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000907 } else if (VD)
908 FuncName = std::string(VD->getName());
909
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000910 std::string BlockNumber = utostr(Blocks.size()-1);
911
Steve Naroff83ba14e2008-10-03 15:04:50 +0000912 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000913 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000914
Steve Naroff83ba14e2008-10-03 15:04:50 +0000915 std::string FunkTypeStr;
916
917 // Get a pointer to the function type so we can cast appropriately.
918 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
919
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000920 // Rewrite the closure block with a compound literal. The first cast is
921 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000922 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000923
Steve Naroff83ba14e2008-10-03 15:04:50 +0000924 Init += ")&" + Tag;
925
926 // Initialize the block function.
927 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000928
929 // Add initializers for any closure decl refs.
930 if (BlockDeclRefs.size()) {
931 // Output all "by copy" declarations.
932 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
933 E = BlockByCopyDecls.end(); I != E; ++I) {
934 Init += ",";
935 if (isObjCType((*I)->getType())) {
936 Init += "[[";
937 Init += (*I)->getName();
938 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000939 } else if (isBlockPointerType((*I)->getType())) {
940 Init += "(void *)";
941 Init += (*I)->getName();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000942 } else {
943 Init += (*I)->getName();
944 }
945 }
946 // Output all "by ref" declarations.
947 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
948 E = BlockByRefDecls.end(); I != E; ++I) {
949 Init += ",&";
950 Init += (*I)->getName();
951 }
952 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000953 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000954 BlockDeclRefs.clear();
955 BlockByRefDecls.clear();
956 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000957 ImportedBlockDecls.clear();
958
Steve Naroff70f95502008-10-04 17:06:23 +0000959 return Init;
960}
961
962//===----------------------------------------------------------------------===//
963// Function Body / Expression rewriting
964//===----------------------------------------------------------------------===//
965
966Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
967 // Start by rewriting all children.
968 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
969 CI != E; ++CI)
970 if (*CI) {
971 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
972 Stmt *newStmt = RewriteFunctionBody(*CI);
973 if (newStmt)
974 *CI = newStmt;
975
976 // We've just rewritten the block body in place.
977 // Now we snarf the rewritten text and stash it away for later use.
978 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
979 RewrittenBlockExprs[CBE] = S;
980 std::string Init = SynthesizeBlockInitExpr(CBE);
981 // Do the rewrite, using S.size() which contains the rewritten size.
982 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
983 } else {
984 Stmt *newStmt = RewriteFunctionBody(*CI);
985 if (newStmt)
986 *CI = newStmt;
987 }
988 }
989 // Handle specific things.
990 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
991 if (CE->getCallee()->getType()->isBlockPointerType())
992 RewriteBlockCall(CE);
993 }
994 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
995 ScopedDecl *SD = DS->getDecl();
996 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
997 if (isBlockPointerType(ND->getType()))
998 RewriteBlockPointerDecl(ND);
999 }
1000 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1001 if (isBlockPointerType(TD->getUnderlyingType()))
1002 RewriteBlockPointerDecl(TD);
1003 }
1004 }
1005 // Return this stmt unmodified.
1006 return S;
1007}
1008
1009/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1010/// main file of the input.
1011void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1012 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1013
1014 // Since function prototypes don't have ParmDecl's, we check the function
1015 // prototype. This enables us to rewrite function declarations and
1016 // definitions using the same code.
1017 QualType funcType = FD->getType();
1018
1019 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
1020 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
1021 E = fproto->arg_type_end(); I && (I != E); ++I)
1022 if (isBlockPointerType(*I)) {
1023 // All the args are checked/rewritten. Don't call twice!
1024 RewriteBlockPointerDecl(FD);
1025 break;
1026 }
1027 }
1028 if (Stmt *Body = FD->getBody()) {
1029 CurFunctionDef = FD;
1030 FD->setBody(RewriteFunctionBody(Body));
1031 // This synthesizes and inserts the block "impl" struct, invoke function,
1032 // and any copy/dispose helper functions.
1033 InsertBlockLiteralsWithinFunction(FD);
1034 CurFunctionDef = 0;
1035 }
1036 return;
1037 }
1038 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1039 RewriteMethodDecl(MD);
1040 if (Stmt *Body = MD->getBody()) {
1041 CurMethodDef = MD;
1042 RewriteFunctionBody(Body);
1043 InsertBlockLiteralsWithinMethod(MD);
1044 CurMethodDef = 0;
1045 }
1046 }
1047 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1048 if (isBlockPointerType(VD->getType())) {
1049 RewriteBlockPointerDecl(VD);
1050 if (VD->getInit()) {
1051 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
1052 RewriteFunctionBody(VD->getInit());
1053
1054 // We've just rewritten the block body in place.
1055 // Now we snarf the rewritten text and stash it away for later use.
1056 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1057 RewrittenBlockExprs[CBE] = S;
1058 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1059 // Do the rewrite, using S.size() which contains the rewritten size.
1060 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1061 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
1062 }
1063 }
1064 }
1065 return;
1066 }
1067 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1068 if (isBlockPointerType(TD->getUnderlyingType()))
1069 RewriteBlockPointerDecl(TD);
1070 return;
1071 }
1072 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1073 if (RD->isDefinition()) {
1074 for (RecordDecl::field_const_iterator i = RD->field_begin(),
1075 e = RD->field_end(); i != e; ++i) {
1076 FieldDecl *FD = *i;
1077 if (isBlockPointerType(FD->getType()))
1078 RewriteBlockPointerDecl(FD);
1079 }
1080 }
1081 return;
1082 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001083}