blob: 103072cff6be9b5b80c2a213f25f2a1b5a5b08a1 [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;
52
53 // The function/method we are rewriting.
54 FunctionDecl *CurFunctionDef;
55 ObjCMethodDecl *CurMethodDef;
56
57 bool IsHeader;
Steve Naroff13188952008-09-18 14:10:13 +000058 std::string InFileName;
59 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000060
61 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000062public:
Steve Naroff13188952008-09-18 14:10:13 +000063 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
64 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.
84 virtual void HandleTopLevelDecl(Decl *D);
85 void HandleDeclInMainFile(Decl *D);
86
87 // Top level
88 Stmt *RewriteFunctionBody(Stmt *S);
89 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
90 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
91
92 // Block specific rewrite rules.
Steve Naroff9c3c9022008-09-17 18:37:59 +000093 void RewriteBlockExpr(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000094
95 void RewriteBlockCall(CallExpr *Exp);
96 void RewriteBlockPointerDecl(NamedDecl *VD);
97 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
98
99 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
100 const char *funcName, std::string Tag);
101 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag);
102 std::string SynthesizeBlockCall(CallExpr *Exp);
103 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
104 const char *FunName);
105
106 void GetBlockDeclRefExprs(Stmt *S);
107 void GetBlockCallExprs(Stmt *S);
108
109 // We avoid calling Type::isBlockPointerType(), since it operates on the
110 // canonical type. We only care if the top-level type is a closure pointer.
111 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
112
113 // FIXME: This predicate seems like it would be useful to add to ASTContext.
114 bool isObjCType(QualType T) {
115 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
116 return false;
117
118 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
119
120 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
121 OCT == Context->getCanonicalType(Context->getObjCClassType()))
122 return true;
123
124 if (const PointerType *PT = OCT->getAsPointerType()) {
125 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
126 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
127 return true;
128 }
129 return false;
130 }
131 // ObjC rewrite methods.
132 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
133 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
134 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
135 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffeab5f632008-09-23 19:24:41 +0000136
137 bool BlockPointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000138 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000139};
140
141}
142
143static bool IsHeaderFile(const std::string &Filename) {
144 std::string::size_type DotPos = Filename.rfind('.');
145
146 if (DotPos == std::string::npos) {
147 // no file extension
148 return false;
149 }
150
151 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
152 // C header: .h
153 // C++ header: .hh or .H;
154 return Ext == "h" || Ext == "hh" || Ext == "H";
155}
156
Steve Naroff13188952008-09-18 14:10:13 +0000157RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile,
158 Diagnostic &D, const LangOptions &LOpts) :
159 Diags(D), LangOpts(LOpts) {
160 IsHeader = IsHeaderFile(inFile);
161 InFileName = inFile;
162 OutFileName = outFile;
163 CurFunctionDef = 0;
164 CurMethodDef = 0;
165 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
166 "rewriting failed");
167 NoNestedBlockCalls = Diags.getCustomDiagID(Diagnostic::Warning,
168 "Rewrite support for closure calls nested within closure blocks is incomplete");
169}
170
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000171ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
Steve Naroff13188952008-09-18 14:10:13 +0000172 const std::string& OutFile,
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000173 Diagnostic &Diags,
174 const LangOptions &LangOpts) {
Steve Naroff13188952008-09-18 14:10:13 +0000175 return new RewriteBlocks(InFile, OutFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000176}
177
178void RewriteBlocks::Initialize(ASTContext &context) {
179 Context = &context;
180 SM = &Context->getSourceManager();
181
182 // Get the ID and start/end of the main file.
183 MainFileID = SM->getMainFileID();
184 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
185 MainFileStart = MainBuf->getBufferStart();
186 MainFileEnd = MainBuf->getBufferEnd();
187
188 Rewrite.setSourceMgr(Context->getSourceManager());
189
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000190 if (IsHeader)
191 Preamble = "#pragma once\n";
192 Preamble += "#ifndef BLOCK_IMPL\n";
193 Preamble += "#define BLOCK_IMPL\n";
194 Preamble += "struct __block_impl {\n";
195 Preamble += " void *isa;\n";
196 Preamble += " int Flags;\n";
197 Preamble += " int Size;\n";
198 Preamble += " void *FuncPtr;\n";
199 Preamble += "};\n";
200 Preamble += "enum {\n";
201 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
202 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
203 Preamble += "};\n";
204 if (LangOpts.Microsoft)
205 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
206 else
207 Preamble += "#define __OBJC_RW_EXTERN extern\n";
208 Preamble += "// Runtime copy/destroy helper functions\n";
209 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
210 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
211 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
212 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000213 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
214 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000215 Preamble += "#endif\n";
216
217 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
218 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000219}
220
221void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
222 unsigned StrLen)
223{
224 if (!Rewrite.InsertText(Loc, StrData, StrLen))
225 return;
226 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
227}
228
229void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
230 const char *NewStr, unsigned NewLength) {
231 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
232 return;
233 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
234}
235
236void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
237 bool haveBlockPtrs = false;
238 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
239 E = Method->param_end(); I != E; ++I)
240 if (isBlockPointerType((*I)->getType()))
241 haveBlockPtrs = true;
242
243 if (!haveBlockPtrs)
244 return;
245
246 // Do a fuzzy rewrite.
247 // We have 1 or more arguments that have closure pointers.
248 SourceLocation Loc = Method->getLocStart();
249 SourceLocation LocEnd = Method->getLocEnd();
250 const char *startBuf = SM->getCharacterData(Loc);
251 const char *endBuf = SM->getCharacterData(LocEnd);
252
253 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000254 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000255
256 while (*methodPtr++ && (methodPtr != endBuf)) {
257 switch (*methodPtr) {
258 case ':':
259 methodPtr++;
260 if (*methodPtr == '(') {
261 const char *scanType = ++methodPtr;
262 bool foundBlockPointer = false;
263 unsigned parenCount = 1;
264
265 while (parenCount) {
266 switch (*scanType) {
267 case '(':
268 parenCount++;
269 break;
270 case ')':
271 parenCount--;
272 break;
273 case '^':
274 foundBlockPointer = true;
275 break;
276 }
277 scanType++;
278 }
279 if (foundBlockPointer) {
280 // advance the location to startArgList.
281 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
282 assert((Loc.isValid()) && "Invalid Loc");
283 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
284
285 // Advance startBuf. Since the underlying buffer has changed,
286 // it's very important to advance startBuf (so we can correctly
287 // compute a relative Loc the next time around).
288 startBuf = methodPtr;
289 }
290 // Advance the method ptr to the end of the type.
291 methodPtr = scanType;
292 }
293 break;
294 }
295 }
296 return;
297}
298
299void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
300 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
301 E = ClassDecl->instmeth_end(); I != E; ++I)
302 RewriteMethodDecl(*I);
303 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
304 E = ClassDecl->classmeth_end(); I != E; ++I)
305 RewriteMethodDecl(*I);
306}
307
308void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
309 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
310 E = CatDecl->instmeth_end(); I != E; ++I)
311 RewriteMethodDecl(*I);
312 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
313 E = CatDecl->classmeth_end(); I != E; ++I)
314 RewriteMethodDecl(*I);
315}
316
317void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
318 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
319 E = PDecl->instmeth_end(); I != E; ++I)
320 RewriteMethodDecl(*I);
321 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
322 E = PDecl->classmeth_end(); I != E; ++I)
323 RewriteMethodDecl(*I);
324}
325
326//===----------------------------------------------------------------------===//
327// Top Level Driver Code
328//===----------------------------------------------------------------------===//
329
330void RewriteBlocks::HandleTopLevelDecl(Decl *D) {
331 // Two cases: either the decl could be in the main file, or it could be in a
332 // #included file. If the former, rewrite it now. If the later, check to see
333 // if we rewrote the #include/#import.
334 SourceLocation Loc = D->getLocation();
335 Loc = SM->getLogicalLoc(Loc);
336
337 // If this is for a builtin, ignore it.
338 if (Loc.isInvalid()) return;
339
340 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
341 RewriteInterfaceDecl(MD);
342 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
343 RewriteCategoryDecl(CD);
344 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
345 RewriteProtocolDecl(PD);
346
347 // If we have a decl in the main file, see if we should rewrite it.
348 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
349 HandleDeclInMainFile(D);
350 return;
351}
352
353std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
354 const char *funcName,
355 std::string Tag) {
356 const FunctionType *AFT = CE->getFunctionType();
357 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000358 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000359 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000360 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000361
362 if (isa<FunctionTypeNoProto>(AFT)) {
363 S += "()";
364 } else if (CE->arg_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000365 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000366 } else {
367 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
368 assert(FT && "SynthesizeBlockFunc: No function proto");
369 S += '(';
370 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000371 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000372 std::string ParamStr;
Steve Naroff9c3c9022008-09-17 18:37:59 +0000373 for (BlockExpr::arg_iterator AI = CE->arg_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000374 E = CE->arg_end(); AI != E; ++AI) {
375 if (AI != CE->arg_begin()) S += ", ";
376 ParamStr = (*AI)->getName();
377 (*AI)->getType().getAsStringInternal(ParamStr);
378 S += ParamStr;
379 }
380 if (FT->isVariadic()) {
381 if (!CE->arg_empty()) S += ", ";
382 S += "...";
383 }
384 S += ')';
385 }
386 S += " {\n";
387
388 bool haveByRefDecls = false;
389
390 // Create local declarations to avoid rewriting all closure decl ref exprs.
391 // First, emit a declaration for all "by ref" decls.
392 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
393 E = BlockByRefDecls.end(); I != E; ++I) {
394 // Note: It is not possible to have "by ref" closure pointer decls.
395 haveByRefDecls = true;
396 S += " ";
397 std::string Name = (*I)->getName();
398 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
399 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
400 }
401 // Next, emit a declaration for all "by copy" declarations.
402 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
403 E = BlockByCopyDecls.end(); I != E; ++I) {
404 S += " ";
405 std::string Name = (*I)->getName();
406 // Handle nested closure invocation. For example:
407 //
408 // void (^myImportedClosure)(void);
409 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
410 //
411 // void (^anotherClosure)(void);
412 // anotherClosure = ^(void) {
413 // myImportedClosure(); // import and invoke the closure
414 // };
415 //
416 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000417 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000418 else
419 (*I)->getType().getAsStringInternal(Name);
420 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
421 }
Steve Naroff9c3c9022008-09-17 18:37:59 +0000422 if (BlockExpr *CBE = dyn_cast<BlockExpr>(CE)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000423 std::string BodyBuf;
424
425 SourceLocation BodyLocStart = CBE->getBody()->getLocStart();
426 SourceLocation BodyLocEnd = CBE->getBody()->getLocEnd();
427 const char *BodyStartBuf = SM->getCharacterData(BodyLocStart);
428 const char *BodyEndBuf = SM->getCharacterData(BodyLocEnd);
429
430 BodyBuf.append(BodyStartBuf, BodyEndBuf-BodyStartBuf+1);
431
432 if (BlockDeclRefs.size()) {
433 unsigned int nCharsAdded = 0;
434 for (unsigned i = 0; i < BlockDeclRefs.size(); i++) {
435 if (BlockDeclRefs[i]->isByRef()) {
436 // Add a level of indirection! The code below assumes
437 // the closure decl refs/locations are in strictly ascending
438 // order. The traversal performed by GetBlockDeclRefExprs()
439 // currently does this. FIXME: Wrap the *x with parens,
440 // just in case x is a more complex expression, like x->member,
441 // which needs to be rewritten to (*x)->member.
442 SourceLocation StarLoc = BlockDeclRefs[i]->getLocStart();
443 const char *StarBuf = SM->getCharacterData(StarLoc);
444 BodyBuf.insert(StarBuf-BodyStartBuf+nCharsAdded, 1, '*');
445 // Get a fresh buffer, the insert might have caused it to grow.
446 BodyStartBuf = SM->getCharacterData(BodyLocStart);
447 nCharsAdded++;
448 } else if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
449 Diags.Report(NoNestedBlockCalls);
450
451 GetBlockCallExprs(CE);
452
453 // Rewrite the closure in place.
454 // The character based equivalent of RewriteBlockCall().
455 // Need to get the CallExpr associated with this BlockDeclRef.
456 std::string BlockCall = SynthesizeBlockCall(BlockCallExprs[BlockDeclRefs[i]]);
457
458 SourceLocation CallLocStart = BlockCallExprs[BlockDeclRefs[i]]->getLocStart();
459 SourceLocation CallLocEnd = BlockCallExprs[BlockDeclRefs[i]]->getLocEnd();
460 const char *CallStart = SM->getCharacterData(CallLocStart);
461 const char *CallEnd = SM->getCharacterData(CallLocEnd);
462 unsigned CallBytes = CallEnd-CallStart;
463 BodyBuf.replace(CallStart-BodyStartBuf, CallBytes, BlockCall.c_str());
464 nCharsAdded += CallBytes;
465 }
466 }
467 }
468 if (haveByRefDecls) {
469 // Remove |...|.
Steve Naroffeab5f632008-09-23 19:24:41 +0000470 //const char *firstBarPtr = strchr(BodyStartBuf, '|');
471 //const char *secondBarPtr = strchr(firstBarPtr+1, '|');
472 //BodyBuf.replace(firstBarPtr-BodyStartBuf, secondBarPtr-firstBarPtr+1, "");
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000473 }
474 S += " ";
475 S += BodyBuf;
476 }
477 S += "\n}\n";
478 return S;
479}
480
Steve Naroff48a8c612008-10-03 12:09:49 +0000481std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag) {
482 std::string S = "struct " + Tag;
483 std::string Constructor = " " + Tag;
484
485 S += " {\n struct __block_impl impl;\n";
486 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000487
488 GetBlockDeclRefExprs(CE);
489 if (BlockDeclRefs.size()) {
490 // Unique all "by copy" declarations.
491 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
492 if (!BlockDeclRefs[i]->isByRef())
493 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
494 // Unique all "by ref" declarations.
495 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
496 if (BlockDeclRefs[i]->isByRef())
497 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
498
499 // Output all "by copy" declarations.
500 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
501 E = BlockByCopyDecls.end(); I != E; ++I) {
502 S += " ";
503 std::string Name = (*I)->getName();
Steve Naroff48a8c612008-10-03 12:09:49 +0000504 std::string ArgName = "_" + Name;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000505 // Handle nested closure invocation. For example:
506 //
507 // void (^myImportedBlock)(void);
508 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
509 //
510 // void (^anotherBlock)(void);
511 // anotherBlock = ^(void) {
512 // myImportedBlock(); // import and invoke the closure
513 // };
514 //
515 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000516 S += "struct __block_impl *";
Steve Naroff48a8c612008-10-03 12:09:49 +0000517 else {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000518 (*I)->getType().getAsStringInternal(Name);
Steve Naroff48a8c612008-10-03 12:09:49 +0000519 (*I)->getType().getAsStringInternal(ArgName);
520 }
521 Constructor += ", " + ArgName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000522 S += Name + ";\n";
523 }
524 // Output all "by ref" declarations.
525 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
526 E = BlockByRefDecls.end(); I != E; ++I) {
527 S += " ";
528 std::string Name = (*I)->getName();
Steve Naroff48a8c612008-10-03 12:09:49 +0000529 std::string ArgName = "_" + Name;
530
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000531 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000532 S += "struct __block_impl *";
Steve Naroff48a8c612008-10-03 12:09:49 +0000533 else {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000534 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Steve Naroff48a8c612008-10-03 12:09:49 +0000535 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
536 }
537 Constructor += ", " + ArgName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000538 S += Name + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000539 }
540 // Finish writing the constructor.
541 // FIXME: handle NSConcreteGlobalBlock.
542 Constructor += ", int flags=0) {\n";
543 Constructor += " impl.isa = &_NSConcreteStackBlock;\n impl.Size = sizeof(";
544 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
545
546 // Initialize all "by copy" arguments.
547 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
548 E = BlockByCopyDecls.end(); I != E; ++I) {
549 std::string Name = (*I)->getName();
550 Constructor += " ";
551 Constructor += Name + " = _";
552 Constructor += Name + ";\n";
553 }
554 // Initialize all "by ref" arguments.
555 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
556 E = BlockByRefDecls.end(); I != E; ++I) {
557 std::string Name = (*I)->getName();
558 Constructor += " ";
559 Constructor += Name + " = _";
560 Constructor += Name + ";\n";
561 }
562 Constructor += " ";
563 Constructor += "}\n";
564 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000565 }
566 S += "};\n";
567 return S;
568}
569
570void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
571 const char *FunName) {
572 // Insert closures that were part of the function.
573 for (unsigned i = 0; i < Blocks.size(); i++) {
574
Steve Naroff48a8c612008-10-03 12:09:49 +0000575 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000576
577 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag);
578
579 InsertText(FunLocStart, CI.c_str(), CI.size());
580
581 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
582
583 InsertText(FunLocStart, CF.c_str(), CF.size());
584
585 BlockDeclRefs.clear();
586 BlockByRefDecls.clear();
587 BlockByCopyDecls.clear();
588 BlockCallExprs.clear();
589 }
590 Blocks.clear();
591}
592
593void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000594 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000595 const char *FuncName = FD->getName();
596
597 SynthesizeBlockLiterals(FunLocStart, FuncName);
598}
599
600void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
601 SourceLocation FunLocStart = MD->getLocStart();
602 std::string FuncName = std::string(MD->getSelector().getName());
603 // Convert colons to underscores.
604 std::string::size_type loc = 0;
605 while ((loc = FuncName.find(":", loc)) != std::string::npos)
606 FuncName.replace(loc, 1, "_");
607
608 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
609}
610
611/// HandleDeclInMainFile - This is called for each top-level decl defined in the
612/// main file of the input.
613void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
615
616 // Since function prototypes don't have ParmDecl's, we check the function
617 // prototype. This enables us to rewrite function declarations and
618 // definitions using the same code.
619 QualType funcType = FD->getType();
620
621 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
622 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
623 E = fproto->arg_type_end(); I && (I != E); ++I)
624 if (isBlockPointerType(*I)) {
625 // All the args are checked/rewritten. Don't call twice!
626 RewriteBlockPointerDecl(FD);
627 break;
628 }
629 }
630 if (Stmt *Body = FD->getBody()) {
631 CurFunctionDef = FD;
632 FD->setBody(RewriteFunctionBody(Body));
633 InsertBlockLiteralsWithinFunction(FD);
634 CurFunctionDef = 0;
635 }
636 return;
637 }
638 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
639 RewriteMethodDecl(MD);
640 if (Stmt *Body = MD->getBody()) {
641 CurMethodDef = MD;
642 RewriteFunctionBody(Body);
643 InsertBlockLiteralsWithinMethod(MD);
644 CurMethodDef = 0;
645 }
646 }
647 if (ValueDecl *ND = dyn_cast<ValueDecl>(D)) {
648 if (isBlockPointerType(ND->getType()))
649 RewriteBlockPointerDecl(ND);
650 return;
651 }
652 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
653 if (isBlockPointerType(TD->getUnderlyingType()))
654 RewriteBlockPointerDecl(TD);
655 return;
656 }
657}
658
659void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
660 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
661 CI != E; ++CI)
662 if (*CI)
663 GetBlockDeclRefExprs(*CI);
664
665 // Handle specific things.
666 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
667 // FIXME: Handle enums.
668 if (!isa<FunctionDecl>(CDRE->getDecl()))
669 BlockDeclRefs.push_back(CDRE);
670 return;
671}
672
673void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
674 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
675 CI != E; ++CI)
676 if (*CI)
677 GetBlockCallExprs(*CI);
678
679 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
680 if (CE->getCallee()->getType()->isBlockPointerType())
681 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
682 }
683 return;
684}
685
686//===----------------------------------------------------------------------===//
687// Function Body / Expression rewriting
688//===----------------------------------------------------------------------===//
689
690Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
691 // Start by rewriting all children.
692 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
693 CI != E; ++CI)
694 if (*CI) {
Steve Naroff9c3c9022008-09-17 18:37:59 +0000695 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000696 // We intentionally avoid rewritting the contents of a closure block
697 // expr. InsertBlockLiteralsWithinFunction() will rewrite the body.
Steve Naroff9c3c9022008-09-17 18:37:59 +0000698 RewriteBlockExpr(CBE);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000699 } else {
700 Stmt *newStmt = RewriteFunctionBody(*CI);
701 if (newStmt)
702 *CI = newStmt;
703 }
704 }
705 // Handle specific things.
706 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
707 if (CE->getCallee()->getType()->isBlockPointerType())
708 RewriteBlockCall(CE);
709 }
710 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
711 ScopedDecl *SD = DS->getDecl();
712 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
713 if (isBlockPointerType(ND->getType()))
714 RewriteBlockPointerDecl(ND);
715 }
716 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
717 if (isBlockPointerType(TD->getUnderlyingType()))
718 RewriteBlockPointerDecl(TD);
719 }
720 }
721 // Return this stmt unmodified.
722 return S;
723}
724
725std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
726 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000727 const char *closureName = 0;
728 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000729
730 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
731 closureName = DRE->getDecl()->getName();
732 CPT = DRE->getType()->getAsBlockPointerType();
733 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
734 closureName = CDRE->getDecl()->getName();
735 CPT = CDRE->getType()->getAsBlockPointerType();
736 } else {
737 assert(1 && "RewriteBlockClass: Bad type");
738 }
739 assert(CPT && "RewriteBlockClass: Bad type");
740 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
741 assert(FT && "RewriteBlockClass: Bad type");
742 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
743 // FTP will be null for closures that don't take arguments.
744
745 // Build a closure call - start with a paren expr to enforce precedence.
746 std::string BlockCall = "(";
747
748 // Synthesize the cast.
749 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000750 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000751 if (FTP) {
752 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
753 E = FTP->arg_type_end(); I && (I != E); ++I)
754 BlockCall += ", " + (*I).getAsString();
755 }
756 BlockCall += "))"; // close the argument list and paren expression.
757
758 // Invoke the closure.
759 BlockCall += closureName;
760 BlockCall += "->Invoke)";
761
762 // Add the arguments.
763 BlockCall += "(";
764 BlockCall += closureName;
765 for (CallExpr::arg_iterator I = Exp->arg_begin(),
766 E = Exp->arg_end(); I != E; ++I) {
767 std::string syncExprBufS;
768 llvm::raw_string_ostream Buf(syncExprBufS);
769 (*I)->printPretty(Buf);
770 BlockCall += ", " + Buf.str();
771 }
772 return BlockCall;
773}
774
775void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
776 std::string BlockCall = SynthesizeBlockCall(Exp);
777
778 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
779 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
780
781 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
782 BlockCall.c_str(), BlockCall.size());
783}
784
785void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
786 SourceLocation DeclLoc = FD->getLocation();
787 unsigned parenCount = 0, nArgs = 0;
788
789 // We have 1 or more arguments that have closure pointers.
790 const char *startBuf = SM->getCharacterData(DeclLoc);
791 const char *startArgList = strchr(startBuf, '(');
792
793 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
794
795 parenCount++;
796 // advance the location to startArgList.
797 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1);
798 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
799
800 const char *topLevelCommaCursor = 0;
801 const char *argPtr = startArgList;
802 bool scannedBlockDecl = false;
Steve Naroff8af6a452008-10-02 17:12:56 +0000803 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000804
805 while (*argPtr++ && parenCount) {
806 switch (*argPtr) {
807 case '^':
808 scannedBlockDecl = true;
809 break;
810 case '(':
811 parenCount++;
812 break;
813 case ')':
814 parenCount--;
815 if (parenCount == 0) {
816 if (scannedBlockDecl) {
817 // If we are rewriting a definition, don't forget the arg name.
818 if (FD->getBody())
819 Tag += FD->getParamDecl(nArgs)->getName();
820 // The last argument is a closure pointer decl, rewrite it!
821 if (topLevelCommaCursor)
822 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size());
823 else
824 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
825 scannedBlockDecl = false; // reset.
826 }
827 nArgs++;
828 }
829 break;
830 case ',':
831 if (parenCount == 1) {
832 // Make sure the function takes more than one argument.
833 assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused");
834 if (scannedBlockDecl) {
835 // If we are rewriting a definition, don't forget the arg name.
836 if (FD->getBody())
837 Tag += FD->getParamDecl(nArgs)->getName();
838 // The current argument is a closure pointer decl, rewrite it!
839 if (topLevelCommaCursor)
840 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size());
841 else
842 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
843 scannedBlockDecl = false;
844 }
845 nArgs++;
846 // advance the location to topLevelCommaCursor.
847 if (topLevelCommaCursor)
848 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor);
849 else
850 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1);
851 topLevelCommaCursor = argPtr;
852 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
853 }
854 break;
855 }
856 }
857 return;
858}
859
Steve Naroffeab5f632008-09-23 19:24:41 +0000860bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) {
861 const BlockPointerType *BPT = QT->getAsBlockPointerType();
862 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
863 const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
864 if (FTP) {
865 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
866 E = FTP->arg_type_end(); I != E; ++I)
867 if (isBlockPointerType(*I))
868 return true;
869 }
870 return false;
871}
872
873void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000874 const char *&LParen, const char *&RParen) {
875 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000876 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
877
878 LParen = argPtr; // output the start.
879 argPtr++; // skip past the left paren.
880 unsigned parenCount = 1;
881
882 while (*argPtr && parenCount) {
883 switch (*argPtr) {
884 case '(': parenCount++; break;
885 case ')': parenCount--; break;
886 default: break;
887 }
888 if (parenCount) argPtr++;
889 }
890 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
891 RParen = argPtr; // output the end
892}
893
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000894void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000895 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
896 RewriteBlockPointerFunctionArgs(FD);
897 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000898 }
899 // Handle Variables and Typedefs.
900 SourceLocation DeclLoc = ND->getLocation();
901 QualType DeclT;
902 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
903 DeclT = VD->getType();
904 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
905 DeclT = TDD->getUnderlyingType();
906 else
907 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000908
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000909 const char *startBuf = SM->getCharacterData(DeclLoc);
910 const char *endBuf = startBuf;
911 // scan backward (from the decl location) for the end of the previous decl.
912 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
913 startBuf--;
914 assert((*startBuf == '^') &&
915 "RewriteBlockPointerDecl() scan error: no caret");
916 // Replace the '^' with '*', computing a negative offset.
917 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
918 ReplaceText(DeclLoc, 1, "*", 1);
919
920 if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) {
921 // Replace the '^' with '*' for arguments.
922 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000923 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000924 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000925 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
926 while (argListBegin < argListEnd) {
927 if (*argListBegin == '^') {
928 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
929 ReplaceText(CaretLoc, 1, "*", 1);
930 }
931 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000932 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000933 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000934 return;
935}
936
Steve Naroff9c3c9022008-09-17 18:37:59 +0000937void RewriteBlocks::RewriteBlockExpr(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000938 Blocks.push_back(Exp);
939 bool haveByRefDecls = false;
940
941 // Add initializers for any closure decl refs.
942 GetBlockDeclRefExprs(Exp);
943 if (BlockDeclRefs.size()) {
944 // Unique all "by copy" declarations.
945 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
946 if (!BlockDeclRefs[i]->isByRef())
947 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
948 // Unique all "by ref" declarations.
949 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
950 if (BlockDeclRefs[i]->isByRef()) {
951 haveByRefDecls = true;
952 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
953 }
954 }
955 std::string FuncName;
956
957 if (CurFunctionDef)
958 FuncName = std::string(CurFunctionDef->getName());
959 else if (CurMethodDef) {
960 FuncName = std::string(CurMethodDef->getSelector().getName());
961 // Convert colons to underscores.
962 std::string::size_type loc = 0;
963 while ((loc = FuncName.find(":", loc)) != std::string::npos)
964 FuncName.replace(loc, 1, "_");
965 }
966 std::string BlockNumber = utostr(Blocks.size()-1);
967
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000968 std::string Tag = "struct __" + FuncName + "_block_impl_" + BlockNumber;
969 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000970
971 // Rewrite the closure block with a compound literal. The first cast is
972 // to prevent warnings from the C compiler.
Steve Naroff8af6a452008-10-02 17:12:56 +0000973 std::string Init = "(struct __block_impl *)&(" + Tag + "){{0,";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000974
975 // Initialize the Flags, Size, and Invoke fields.
976 Init += (haveByRefDecls ? "HAS_BYREF," : "0,");
977 Init += "sizeof(" + Tag + ")," + Func + "}";
978
979 // Add initializers for any closure decl refs.
980 if (BlockDeclRefs.size()) {
981 // Output all "by copy" declarations.
982 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
983 E = BlockByCopyDecls.end(); I != E; ++I) {
984 Init += ",";
985 if (isObjCType((*I)->getType())) {
986 Init += "[[";
987 Init += (*I)->getName();
988 Init += " retain] autorelease]";
989 } else {
990 Init += (*I)->getName();
991 }
992 }
993 // Output all "by ref" declarations.
994 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
995 E = BlockByRefDecls.end(); I != E; ++I) {
996 Init += ",&";
997 Init += (*I)->getName();
998 }
999 }
1000 Init += "}";
1001 BlockDeclRefs.clear();
1002 BlockByRefDecls.clear();
1003 BlockByCopyDecls.clear();
1004
1005 // Do the rewrite.
1006 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
1007 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
1008 ReplaceText(Exp->getLocStart(), endBuf-startBuf+1, Init.c_str(), Init.size());
1009 return;
1010}