CodeGenFunction.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
  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. // This coordinates the per-function state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGException.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "clang/AST/APValue.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "llvm/Target/TargetData.h"
  27. #include "llvm/Intrinsics.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
  31. : CodeGenTypeCache(cgm), CGM(cgm),
  32. Target(CGM.getContext().getTargetInfo()), Builder(cgm.getModule().getContext()),
  33. AutoreleaseResult(false), BlockInfo(0), BlockPointer(0),
  34. NormalCleanupDest(0), NextCleanupDestIndex(1),
  35. EHResumeBlock(0), ExceptionSlot(0), EHSelectorSlot(0),
  36. DebugInfo(0), DisableDebugInfo(false), DidCallStackSave(false),
  37. IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
  38. CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
  39. OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
  40. TrapBB(0) {
  41. CatchUndefined = getContext().getLangOptions().CatchUndefined;
  42. CGM.getCXXABI().getMangleContext().startNewFunction();
  43. }
  44. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  45. return CGM.getTypes().ConvertTypeForMem(T);
  46. }
  47. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  48. return CGM.getTypes().ConvertType(T);
  49. }
  50. bool CodeGenFunction::hasAggregateLLVMType(QualType type) {
  51. switch (type.getCanonicalType()->getTypeClass()) {
  52. #define TYPE(name, parent)
  53. #define ABSTRACT_TYPE(name, parent)
  54. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  55. #define DEPENDENT_TYPE(name, parent) case Type::name:
  56. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  57. #include "clang/AST/TypeNodes.def"
  58. llvm_unreachable("non-canonical or dependent type in IR-generation");
  59. case Type::Builtin:
  60. case Type::Pointer:
  61. case Type::BlockPointer:
  62. case Type::LValueReference:
  63. case Type::RValueReference:
  64. case Type::MemberPointer:
  65. case Type::Vector:
  66. case Type::ExtVector:
  67. case Type::FunctionProto:
  68. case Type::FunctionNoProto:
  69. case Type::Enum:
  70. case Type::ObjCObjectPointer:
  71. return false;
  72. // Complexes, arrays, records, and Objective-C objects.
  73. case Type::Complex:
  74. case Type::ConstantArray:
  75. case Type::IncompleteArray:
  76. case Type::VariableArray:
  77. case Type::Record:
  78. case Type::ObjCObject:
  79. case Type::ObjCInterface:
  80. return true;
  81. // In IRGen, atomic types are just the underlying type
  82. case Type::Atomic:
  83. return hasAggregateLLVMType(type->getAs<AtomicType>()->getValueType());
  84. }
  85. llvm_unreachable("unknown type kind!");
  86. }
  87. void CodeGenFunction::EmitReturnBlock() {
  88. // For cleanliness, we try to avoid emitting the return block for
  89. // simple cases.
  90. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  91. if (CurBB) {
  92. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  93. // We have a valid insert point, reuse it if it is empty or there are no
  94. // explicit jumps to the return block.
  95. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  96. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  97. delete ReturnBlock.getBlock();
  98. } else
  99. EmitBlock(ReturnBlock.getBlock());
  100. return;
  101. }
  102. // Otherwise, if the return block is the target of a single direct
  103. // branch then we can just put the code in that block instead. This
  104. // cleans up functions which started with a unified return block.
  105. if (ReturnBlock.getBlock()->hasOneUse()) {
  106. llvm::BranchInst *BI =
  107. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
  108. if (BI && BI->isUnconditional() &&
  109. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  110. // Reset insertion point, including debug location, and delete the branch.
  111. Builder.SetCurrentDebugLocation(BI->getDebugLoc());
  112. Builder.SetInsertPoint(BI->getParent());
  113. BI->eraseFromParent();
  114. delete ReturnBlock.getBlock();
  115. return;
  116. }
  117. }
  118. // FIXME: We are at an unreachable point, there is no reason to emit the block
  119. // unless it has uses. However, we still need a place to put the debug
  120. // region.end for now.
  121. EmitBlock(ReturnBlock.getBlock());
  122. }
  123. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  124. if (!BB) return;
  125. if (!BB->use_empty())
  126. return CGF.CurFn->getBasicBlockList().push_back(BB);
  127. delete BB;
  128. }
  129. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  130. assert(BreakContinueStack.empty() &&
  131. "mismatched push/pop in break/continue stack!");
  132. // Pop any cleanups that might have been associated with the
  133. // parameters. Do this in whatever block we're currently in; it's
  134. // important to do this before we enter the return block or return
  135. // edges will be *really* confused.
  136. if (EHStack.stable_begin() != PrologueCleanupDepth)
  137. PopCleanupBlocks(PrologueCleanupDepth);
  138. // Emit function epilog (to return).
  139. EmitReturnBlock();
  140. if (ShouldInstrumentFunction())
  141. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  142. // Emit debug descriptor for function end.
  143. if (CGDebugInfo *DI = getDebugInfo()) {
  144. DI->setLocation(EndLoc);
  145. DI->EmitFunctionEnd(Builder);
  146. }
  147. EmitFunctionEpilog(*CurFnInfo);
  148. EmitEndEHSpec(CurCodeDecl);
  149. assert(EHStack.empty() &&
  150. "did not remove all scopes from cleanup stack!");
  151. // If someone did an indirect goto, emit the indirect goto block at the end of
  152. // the function.
  153. if (IndirectBranch) {
  154. EmitBlock(IndirectBranch->getParent());
  155. Builder.ClearInsertionPoint();
  156. }
  157. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  158. llvm::Instruction *Ptr = AllocaInsertPt;
  159. AllocaInsertPt = 0;
  160. Ptr->eraseFromParent();
  161. // If someone took the address of a label but never did an indirect goto, we
  162. // made a zero entry PHI node, which is illegal, zap it now.
  163. if (IndirectBranch) {
  164. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  165. if (PN->getNumIncomingValues() == 0) {
  166. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  167. PN->eraseFromParent();
  168. }
  169. }
  170. EmitIfUsed(*this, EHResumeBlock);
  171. EmitIfUsed(*this, TerminateLandingPad);
  172. EmitIfUsed(*this, TerminateHandler);
  173. EmitIfUsed(*this, UnreachableBlock);
  174. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  175. EmitDeclMetadata();
  176. }
  177. /// ShouldInstrumentFunction - Return true if the current function should be
  178. /// instrumented with __cyg_profile_func_* calls
  179. bool CodeGenFunction::ShouldInstrumentFunction() {
  180. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  181. return false;
  182. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  183. return false;
  184. return true;
  185. }
  186. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  187. /// instrumentation function with the current function and the call site, if
  188. /// function instrumentation is enabled.
  189. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  190. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  191. llvm::PointerType *PointerTy = Int8PtrTy;
  192. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  193. llvm::FunctionType *FunctionTy =
  194. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
  195. ProfileFuncArgs, false);
  196. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  197. llvm::CallInst *CallSite = Builder.CreateCall(
  198. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  199. llvm::ConstantInt::get(Int32Ty, 0),
  200. "callsite");
  201. Builder.CreateCall2(F,
  202. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  203. CallSite);
  204. }
  205. void CodeGenFunction::EmitMCountInstrumentation() {
  206. llvm::FunctionType *FTy =
  207. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
  208. llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
  209. Target.getMCountName());
  210. Builder.CreateCall(MCountFn);
  211. }
  212. void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
  213. llvm::Function *Fn,
  214. const CGFunctionInfo &FnInfo,
  215. const FunctionArgList &Args,
  216. SourceLocation StartLoc) {
  217. const Decl *D = GD.getDecl();
  218. DidCallStackSave = false;
  219. CurCodeDecl = CurFuncDecl = D;
  220. FnRetTy = RetTy;
  221. CurFn = Fn;
  222. CurFnInfo = &FnInfo;
  223. assert(CurFn->isDeclaration() && "Function already has body?");
  224. // Pass inline keyword to optimizer if it appears explicitly on any
  225. // declaration.
  226. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  227. for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
  228. RE = FD->redecls_end(); RI != RE; ++RI)
  229. if (RI->isInlineSpecified()) {
  230. Fn->addFnAttr(llvm::Attribute::InlineHint);
  231. break;
  232. }
  233. if (getContext().getLangOptions().OpenCL) {
  234. // Add metadata for a kernel function.
  235. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  236. if (FD->hasAttr<OpenCLKernelAttr>()) {
  237. llvm::LLVMContext &Context = getLLVMContext();
  238. llvm::NamedMDNode *OpenCLMetadata =
  239. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  240. llvm::Value *Op = Fn;
  241. OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Op));
  242. }
  243. }
  244. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  245. // Create a marker to make it easy to insert allocas into the entryblock
  246. // later. Don't create this with the builder, because we don't want it
  247. // folded.
  248. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  249. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  250. if (Builder.isNamePreserving())
  251. AllocaInsertPt->setName("allocapt");
  252. ReturnBlock = getJumpDestInCurrentScope("return");
  253. Builder.SetInsertPoint(EntryBB);
  254. // Emit subprogram debug descriptor.
  255. if (CGDebugInfo *DI = getDebugInfo()) {
  256. unsigned NumArgs = 0;
  257. QualType *ArgsArray = new QualType[Args.size()];
  258. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  259. i != e; ++i) {
  260. ArgsArray[NumArgs++] = (*i)->getType();
  261. }
  262. QualType FnType =
  263. getContext().getFunctionType(RetTy, ArgsArray, NumArgs,
  264. FunctionProtoType::ExtProtoInfo());
  265. delete[] ArgsArray;
  266. DI->setLocation(StartLoc);
  267. DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
  268. }
  269. if (ShouldInstrumentFunction())
  270. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  271. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  272. EmitMCountInstrumentation();
  273. if (RetTy->isVoidType()) {
  274. // Void type; nothing to return.
  275. ReturnValue = 0;
  276. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  277. hasAggregateLLVMType(CurFnInfo->getReturnType())) {
  278. // Indirect aggregate return; emit returned value directly into sret slot.
  279. // This reduces code size, and affects correctness in C++.
  280. ReturnValue = CurFn->arg_begin();
  281. } else {
  282. ReturnValue = CreateIRTemp(RetTy, "retval");
  283. // Tell the epilog emitter to autorelease the result. We do this
  284. // now so that various specialized functions can suppress it
  285. // during their IR-generation.
  286. if (getLangOptions().ObjCAutoRefCount &&
  287. !CurFnInfo->isReturnsRetained() &&
  288. RetTy->isObjCRetainableType())
  289. AutoreleaseResult = true;
  290. }
  291. EmitStartEHSpec(CurCodeDecl);
  292. PrologueCleanupDepth = EHStack.stable_begin();
  293. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  294. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
  295. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  296. // If any of the arguments have a variably modified type, make sure to
  297. // emit the type size.
  298. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  299. i != e; ++i) {
  300. QualType Ty = (*i)->getType();
  301. if (Ty->isVariablyModifiedType())
  302. EmitVariablyModifiedType(Ty);
  303. }
  304. // Emit a location at the end of the prologue.
  305. if (CGDebugInfo *DI = getDebugInfo())
  306. DI->EmitLocation(Builder, StartLoc);
  307. }
  308. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
  309. const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
  310. assert(FD->getBody());
  311. EmitStmt(FD->getBody());
  312. }
  313. /// Tries to mark the given function nounwind based on the
  314. /// non-existence of any throwing calls within it. We believe this is
  315. /// lightweight enough to do at -O0.
  316. static void TryMarkNoThrow(llvm::Function *F) {
  317. // LLVM treats 'nounwind' on a function as part of the type, so we
  318. // can't do this on functions that can be overwritten.
  319. if (F->mayBeOverridden()) return;
  320. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  321. for (llvm::BasicBlock::iterator
  322. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  323. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  324. if (!Call->doesNotThrow())
  325. return;
  326. } else if (isa<llvm::ResumeInst>(&*BI)) {
  327. return;
  328. }
  329. F->setDoesNotThrow(true);
  330. }
  331. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  332. const CGFunctionInfo &FnInfo) {
  333. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  334. // Check if we should generate debug info for this function.
  335. if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
  336. DebugInfo = CGM.getModuleDebugInfo();
  337. FunctionArgList Args;
  338. QualType ResTy = FD->getResultType();
  339. CurGD = GD;
  340. if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
  341. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
  342. if (FD->getNumParams())
  343. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
  344. Args.push_back(FD->getParamDecl(i));
  345. SourceRange BodyRange;
  346. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  347. // Emit the standard function prologue.
  348. StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
  349. // Generate the body of the function.
  350. if (isa<CXXDestructorDecl>(FD))
  351. EmitDestructorBody(Args);
  352. else if (isa<CXXConstructorDecl>(FD))
  353. EmitConstructorBody(Args);
  354. else if (getContext().getLangOptions().CUDA &&
  355. !CGM.getCodeGenOpts().CUDAIsDevice &&
  356. FD->hasAttr<CUDAGlobalAttr>())
  357. CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
  358. else
  359. EmitFunctionBody(Args);
  360. // Emit the standard function epilogue.
  361. FinishFunction(BodyRange.getEnd());
  362. // If we haven't marked the function nothrow through other means, do
  363. // a quick pass now to see if we can.
  364. if (!CurFn->doesNotThrow())
  365. TryMarkNoThrow(CurFn);
  366. }
  367. /// ContainsLabel - Return true if the statement contains a label in it. If
  368. /// this statement is not executed normally, it not containing a label means
  369. /// that we can just remove the code.
  370. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  371. // Null statement, not a label!
  372. if (S == 0) return false;
  373. // If this is a label, we have to emit the code, consider something like:
  374. // if (0) { ... foo: bar(); } goto foo;
  375. //
  376. // TODO: If anyone cared, we could track __label__'s, since we know that you
  377. // can't jump to one from outside their declared region.
  378. if (isa<LabelStmt>(S))
  379. return true;
  380. // If this is a case/default statement, and we haven't seen a switch, we have
  381. // to emit the code.
  382. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  383. return true;
  384. // If this is a switch statement, we want to ignore cases below it.
  385. if (isa<SwitchStmt>(S))
  386. IgnoreCaseStmts = true;
  387. // Scan subexpressions for verboten labels.
  388. for (Stmt::const_child_range I = S->children(); I; ++I)
  389. if (ContainsLabel(*I, IgnoreCaseStmts))
  390. return true;
  391. return false;
  392. }
  393. /// containsBreak - Return true if the statement contains a break out of it.
  394. /// If the statement (recursively) contains a switch or loop with a break
  395. /// inside of it, this is fine.
  396. bool CodeGenFunction::containsBreak(const Stmt *S) {
  397. // Null statement, not a label!
  398. if (S == 0) return false;
  399. // If this is a switch or loop that defines its own break scope, then we can
  400. // include it and anything inside of it.
  401. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  402. isa<ForStmt>(S))
  403. return false;
  404. if (isa<BreakStmt>(S))
  405. return true;
  406. // Scan subexpressions for verboten breaks.
  407. for (Stmt::const_child_range I = S->children(); I; ++I)
  408. if (containsBreak(*I))
  409. return true;
  410. return false;
  411. }
  412. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  413. /// to a constant, or if it does but contains a label, return false. If it
  414. /// constant folds return true and set the boolean result in Result.
  415. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  416. bool &ResultBool) {
  417. llvm::APInt ResultInt;
  418. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  419. return false;
  420. ResultBool = ResultInt.getBoolValue();
  421. return true;
  422. }
  423. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  424. /// to a constant, or if it does but contains a label, return false. If it
  425. /// constant folds return true and set the folded value.
  426. bool CodeGenFunction::
  427. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
  428. // FIXME: Rename and handle conversion of other evaluatable things
  429. // to bool.
  430. Expr::EvalResult Result;
  431. if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
  432. Result.HasSideEffects)
  433. return false; // Not foldable, not integer or not fully evaluatable.
  434. if (CodeGenFunction::ContainsLabel(Cond))
  435. return false; // Contains a label.
  436. ResultInt = Result.Val.getInt();
  437. return true;
  438. }
  439. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  440. /// statement) to the specified blocks. Based on the condition, this might try
  441. /// to simplify the codegen of the conditional based on the branch.
  442. ///
  443. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  444. llvm::BasicBlock *TrueBlock,
  445. llvm::BasicBlock *FalseBlock) {
  446. Cond = Cond->IgnoreParens();
  447. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  448. // Handle X && Y in a condition.
  449. if (CondBOp->getOpcode() == BO_LAnd) {
  450. // If we have "1 && X", simplify the code. "0 && X" would have constant
  451. // folded if the case was simple enough.
  452. bool ConstantBool = false;
  453. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  454. ConstantBool) {
  455. // br(1 && X) -> br(X).
  456. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  457. }
  458. // If we have "X && 1", simplify the code to use an uncond branch.
  459. // "X && 0" would have been constant folded to 0.
  460. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  461. ConstantBool) {
  462. // br(X && 1) -> br(X).
  463. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  464. }
  465. // Emit the LHS as a conditional. If the LHS conditional is false, we
  466. // want to jump to the FalseBlock.
  467. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  468. ConditionalEvaluation eval(*this);
  469. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
  470. EmitBlock(LHSTrue);
  471. // Any temporaries created here are conditional.
  472. eval.begin(*this);
  473. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  474. eval.end(*this);
  475. return;
  476. }
  477. if (CondBOp->getOpcode() == BO_LOr) {
  478. // If we have "0 || X", simplify the code. "1 || X" would have constant
  479. // folded if the case was simple enough.
  480. bool ConstantBool = false;
  481. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  482. !ConstantBool) {
  483. // br(0 || X) -> br(X).
  484. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  485. }
  486. // If we have "X || 0", simplify the code to use an uncond branch.
  487. // "X || 1" would have been constant folded to 1.
  488. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  489. !ConstantBool) {
  490. // br(X || 0) -> br(X).
  491. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  492. }
  493. // Emit the LHS as a conditional. If the LHS conditional is true, we
  494. // want to jump to the TrueBlock.
  495. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  496. ConditionalEvaluation eval(*this);
  497. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
  498. EmitBlock(LHSFalse);
  499. // Any temporaries created here are conditional.
  500. eval.begin(*this);
  501. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  502. eval.end(*this);
  503. return;
  504. }
  505. }
  506. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  507. // br(!x, t, f) -> br(x, f, t)
  508. if (CondUOp->getOpcode() == UO_LNot)
  509. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
  510. }
  511. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  512. // Handle ?: operator.
  513. // Just ignore GNU ?: extension.
  514. if (CondOp->getLHS()) {
  515. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  516. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  517. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  518. ConditionalEvaluation cond(*this);
  519. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
  520. cond.begin(*this);
  521. EmitBlock(LHSBlock);
  522. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
  523. cond.end(*this);
  524. cond.begin(*this);
  525. EmitBlock(RHSBlock);
  526. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
  527. cond.end(*this);
  528. return;
  529. }
  530. }
  531. // Emit the code with the fully general case.
  532. llvm::Value *CondV = EvaluateExprAsBool(Cond);
  533. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  534. }
  535. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  536. /// specified stmt yet.
  537. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
  538. bool OmitOnError) {
  539. CGM.ErrorUnsupported(S, Type, OmitOnError);
  540. }
  541. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  542. /// variable-length array whose elements have a non-zero bit-pattern.
  543. ///
  544. /// \param src - a char* pointing to the bit-pattern for a single
  545. /// base element of the array
  546. /// \param sizeInChars - the total size of the VLA, in chars
  547. /// \param align - the total alignment of the VLA
  548. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  549. llvm::Value *dest, llvm::Value *src,
  550. llvm::Value *sizeInChars) {
  551. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  552. = CGF.getContext().getTypeInfoInChars(baseType);
  553. CGBuilderTy &Builder = CGF.Builder;
  554. llvm::Value *baseSizeInChars
  555. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  556. llvm::Type *i8p = Builder.getInt8PtrTy();
  557. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  558. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  559. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  560. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  561. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  562. // Make a loop over the VLA. C99 guarantees that the VLA element
  563. // count must be nonzero.
  564. CGF.EmitBlock(loopBB);
  565. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  566. cur->addIncoming(begin, originBB);
  567. // memcpy the individual element bit-pattern.
  568. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  569. baseSizeAndAlign.second.getQuantity(),
  570. /*volatile*/ false);
  571. // Go to the next element.
  572. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
  573. // Leave if that's the end of the VLA.
  574. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  575. Builder.CreateCondBr(done, contBB, loopBB);
  576. cur->addIncoming(next, loopBB);
  577. CGF.EmitBlock(contBB);
  578. }
  579. void
  580. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  581. // Ignore empty classes in C++.
  582. if (getContext().getLangOptions().CPlusPlus) {
  583. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  584. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  585. return;
  586. }
  587. }
  588. // Cast the dest ptr to the appropriate i8 pointer type.
  589. unsigned DestAS =
  590. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  591. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  592. if (DestPtr->getType() != BP)
  593. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  594. // Get size and alignment info for this aggregate.
  595. std::pair<CharUnits, CharUnits> TypeInfo =
  596. getContext().getTypeInfoInChars(Ty);
  597. CharUnits Size = TypeInfo.first;
  598. CharUnits Align = TypeInfo.second;
  599. llvm::Value *SizeVal;
  600. const VariableArrayType *vla;
  601. // Don't bother emitting a zero-byte memset.
  602. if (Size.isZero()) {
  603. // But note that getTypeInfo returns 0 for a VLA.
  604. if (const VariableArrayType *vlaType =
  605. dyn_cast_or_null<VariableArrayType>(
  606. getContext().getAsArrayType(Ty))) {
  607. QualType eltType;
  608. llvm::Value *numElts;
  609. llvm::tie(numElts, eltType) = getVLASize(vlaType);
  610. SizeVal = numElts;
  611. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  612. if (!eltSize.isOne())
  613. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  614. vla = vlaType;
  615. } else {
  616. return;
  617. }
  618. } else {
  619. SizeVal = CGM.getSize(Size);
  620. vla = 0;
  621. }
  622. // If the type contains a pointer to data member we can't memset it to zero.
  623. // Instead, create a null constant and copy it to the destination.
  624. // TODO: there are other patterns besides zero that we can usefully memset,
  625. // like -1, which happens to be the pattern used by member-pointers.
  626. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  627. // For a VLA, emit a single element, then splat that over the VLA.
  628. if (vla) Ty = getContext().getBaseElementType(vla);
  629. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  630. llvm::GlobalVariable *NullVariable =
  631. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  632. /*isConstant=*/true,
  633. llvm::GlobalVariable::PrivateLinkage,
  634. NullConstant, Twine());
  635. llvm::Value *SrcPtr =
  636. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  637. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  638. // Get and call the appropriate llvm.memcpy overload.
  639. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  640. return;
  641. }
  642. // Otherwise, just memset the whole thing to zero. This is legal
  643. // because in LLVM, all default initializers (other than the ones we just
  644. // handled above) are guaranteed to have a bit pattern of all zeros.
  645. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  646. Align.getQuantity(), false);
  647. }
  648. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  649. // Make sure that there is a block for the indirect goto.
  650. if (IndirectBranch == 0)
  651. GetIndirectGotoBlock();
  652. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  653. // Make sure the indirect branch includes all of the address-taken blocks.
  654. IndirectBranch->addDestination(BB);
  655. return llvm::BlockAddress::get(CurFn, BB);
  656. }
  657. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  658. // If we already made the indirect branch for indirect goto, return its block.
  659. if (IndirectBranch) return IndirectBranch->getParent();
  660. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  661. // Create the PHI node that indirect gotos will add entries to.
  662. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  663. "indirect.goto.dest");
  664. // Create the indirect branch instruction.
  665. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  666. return IndirectBranch->getParent();
  667. }
  668. /// Computes the length of an array in elements, as well as the base
  669. /// element type and a properly-typed first element pointer.
  670. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  671. QualType &baseType,
  672. llvm::Value *&addr) {
  673. const ArrayType *arrayType = origArrayType;
  674. // If it's a VLA, we have to load the stored size. Note that
  675. // this is the size of the VLA in bytes, not its size in elements.
  676. llvm::Value *numVLAElements = 0;
  677. if (isa<VariableArrayType>(arrayType)) {
  678. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  679. // Walk into all VLAs. This doesn't require changes to addr,
  680. // which has type T* where T is the first non-VLA element type.
  681. do {
  682. QualType elementType = arrayType->getElementType();
  683. arrayType = getContext().getAsArrayType(elementType);
  684. // If we only have VLA components, 'addr' requires no adjustment.
  685. if (!arrayType) {
  686. baseType = elementType;
  687. return numVLAElements;
  688. }
  689. } while (isa<VariableArrayType>(arrayType));
  690. // We get out here only if we find a constant array type
  691. // inside the VLA.
  692. }
  693. // We have some number of constant-length arrays, so addr should
  694. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  695. // down to the first element of addr.
  696. SmallVector<llvm::Value*, 8> gepIndices;
  697. // GEP down to the array type.
  698. llvm::ConstantInt *zero = Builder.getInt32(0);
  699. gepIndices.push_back(zero);
  700. // It's more efficient to calculate the count from the LLVM
  701. // constant-length arrays than to re-evaluate the array bounds.
  702. uint64_t countFromCLAs = 1;
  703. llvm::ArrayType *llvmArrayType =
  704. cast<llvm::ArrayType>(
  705. cast<llvm::PointerType>(addr->getType())->getElementType());
  706. while (true) {
  707. assert(isa<ConstantArrayType>(arrayType));
  708. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  709. == llvmArrayType->getNumElements());
  710. gepIndices.push_back(zero);
  711. countFromCLAs *= llvmArrayType->getNumElements();
  712. llvmArrayType =
  713. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  714. if (!llvmArrayType) break;
  715. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  716. assert(arrayType && "LLVM and Clang types are out-of-synch");
  717. }
  718. baseType = arrayType->getElementType();
  719. // Create the actual GEP.
  720. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  721. llvm::Value *numElements
  722. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  723. // If we had any VLA dimensions, factor them in.
  724. if (numVLAElements)
  725. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  726. return numElements;
  727. }
  728. std::pair<llvm::Value*, QualType>
  729. CodeGenFunction::getVLASize(QualType type) {
  730. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  731. assert(vla && "type was not a variable array type!");
  732. return getVLASize(vla);
  733. }
  734. std::pair<llvm::Value*, QualType>
  735. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  736. // The number of elements so far; always size_t.
  737. llvm::Value *numElements = 0;
  738. QualType elementType;
  739. do {
  740. elementType = type->getElementType();
  741. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  742. assert(vlaSize && "no size for VLA!");
  743. assert(vlaSize->getType() == SizeTy);
  744. if (!numElements) {
  745. numElements = vlaSize;
  746. } else {
  747. // It's undefined behavior if this wraps around, so mark it that way.
  748. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  749. }
  750. } while ((type = getContext().getAsVariableArrayType(elementType)));
  751. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  752. }
  753. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  754. assert(type->isVariablyModifiedType() &&
  755. "Must pass variably modified type to EmitVLASizes!");
  756. EnsureInsertPoint();
  757. // We're going to walk down into the type and look for VLA
  758. // expressions.
  759. type = type.getCanonicalType();
  760. do {
  761. assert(type->isVariablyModifiedType());
  762. const Type *ty = type.getTypePtr();
  763. switch (ty->getTypeClass()) {
  764. #define TYPE(Class, Base)
  765. #define ABSTRACT_TYPE(Class, Base)
  766. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  767. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  768. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  769. #include "clang/AST/TypeNodes.def"
  770. llvm_unreachable("unexpected dependent or non-canonical type!");
  771. // These types are never variably-modified.
  772. case Type::Builtin:
  773. case Type::Complex:
  774. case Type::Vector:
  775. case Type::ExtVector:
  776. case Type::Record:
  777. case Type::Enum:
  778. case Type::ObjCObject:
  779. case Type::ObjCInterface:
  780. case Type::ObjCObjectPointer:
  781. llvm_unreachable("type class is never variably-modified!");
  782. case Type::Pointer:
  783. type = cast<PointerType>(ty)->getPointeeType();
  784. break;
  785. case Type::BlockPointer:
  786. type = cast<BlockPointerType>(ty)->getPointeeType();
  787. break;
  788. case Type::LValueReference:
  789. case Type::RValueReference:
  790. type = cast<ReferenceType>(ty)->getPointeeType();
  791. break;
  792. case Type::MemberPointer:
  793. type = cast<MemberPointerType>(ty)->getPointeeType();
  794. break;
  795. case Type::ConstantArray:
  796. case Type::IncompleteArray:
  797. // Losing element qualification here is fine.
  798. type = cast<ArrayType>(ty)->getElementType();
  799. break;
  800. case Type::VariableArray: {
  801. // Losing element qualification here is fine.
  802. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  803. // Unknown size indication requires no size computation.
  804. // Otherwise, evaluate and record it.
  805. if (const Expr *size = vat->getSizeExpr()) {
  806. // It's possible that we might have emitted this already,
  807. // e.g. with a typedef and a pointer to it.
  808. llvm::Value *&entry = VLASizeMap[size];
  809. if (!entry) {
  810. // Always zexting here would be wrong if it weren't
  811. // undefined behavior to have a negative bound.
  812. entry = Builder.CreateIntCast(EmitScalarExpr(size), SizeTy,
  813. /*signed*/ false);
  814. }
  815. }
  816. type = vat->getElementType();
  817. break;
  818. }
  819. case Type::FunctionProto:
  820. case Type::FunctionNoProto:
  821. type = cast<FunctionType>(ty)->getResultType();
  822. break;
  823. case Type::Atomic:
  824. type = cast<AtomicType>(ty)->getValueType();
  825. break;
  826. }
  827. } while (type->isVariablyModifiedType());
  828. }
  829. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  830. if (getContext().getBuiltinVaListType()->isArrayType())
  831. return EmitScalarExpr(E);
  832. return EmitLValue(E).getAddress();
  833. }
  834. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  835. llvm::Constant *Init) {
  836. assert (Init && "Invalid DeclRefExpr initializer!");
  837. if (CGDebugInfo *Dbg = getDebugInfo())
  838. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  839. }
  840. CodeGenFunction::PeepholeProtection
  841. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  842. // At the moment, the only aggressive peephole we do in IR gen
  843. // is trunc(zext) folding, but if we add more, we can easily
  844. // extend this protection.
  845. if (!rvalue.isScalar()) return PeepholeProtection();
  846. llvm::Value *value = rvalue.getScalarVal();
  847. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  848. // Just make an extra bitcast.
  849. assert(HaveInsertPoint());
  850. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  851. Builder.GetInsertBlock());
  852. PeepholeProtection protection;
  853. protection.Inst = inst;
  854. return protection;
  855. }
  856. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  857. if (!protection.Inst) return;
  858. // In theory, we could try to duplicate the peepholes now, but whatever.
  859. protection.Inst->eraseFromParent();
  860. }
  861. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  862. llvm::Value *AnnotatedVal,
  863. llvm::StringRef AnnotationStr,
  864. SourceLocation Location) {
  865. llvm::Value *Args[4] = {
  866. AnnotatedVal,
  867. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  868. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  869. CGM.EmitAnnotationLineNo(Location)
  870. };
  871. return Builder.CreateCall(AnnotationFn, Args);
  872. }
  873. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  874. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  875. // FIXME We create a new bitcast for every annotation because that's what
  876. // llvm-gcc was doing.
  877. for (specific_attr_iterator<AnnotateAttr>
  878. ai = D->specific_attr_begin<AnnotateAttr>(),
  879. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  880. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  881. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  882. (*ai)->getAnnotation(), D->getLocation());
  883. }
  884. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  885. llvm::Value *V) {
  886. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  887. llvm::Type *VTy = V->getType();
  888. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  889. CGM.Int8PtrTy);
  890. for (specific_attr_iterator<AnnotateAttr>
  891. ai = D->specific_attr_begin<AnnotateAttr>(),
  892. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
  893. // FIXME Always emit the cast inst so we can differentiate between
  894. // annotation on the first field of a struct and annotation on the struct
  895. // itself.
  896. if (VTy != CGM.Int8PtrTy)
  897. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  898. V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
  899. V = Builder.CreateBitCast(V, VTy);
  900. }
  901. return V;
  902. }