CodeGenFunction.cpp 40 KB

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