CodeGenFunction.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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 "CGCXXABI.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGException.h"
  18. #include "clang/Basic/TargetInfo.h"
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Decl.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "llvm/Target/TargetData.h"
  26. #include "llvm/Intrinsics.h"
  27. using namespace clang;
  28. using namespace CodeGen;
  29. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
  30. : CodeGenTypeCache(cgm), CGM(cgm),
  31. Target(CGM.getContext().Target), Builder(cgm.getModule().getContext()),
  32. BlockInfo(0), BlockPointer(0),
  33. NormalCleanupDest(0), EHCleanupDest(0), NextCleanupDestIndex(1),
  34. ExceptionSlot(0), DebugInfo(0), DisableDebugInfo(false), IndirectBranch(0),
  35. SwitchInsn(0), CaseRangeBlock(0),
  36. DidCallStackSave(false), UnreachableBlock(0),
  37. CXXThisDecl(0), CXXThisValue(0), CXXVTTDecl(0), CXXVTTValue(0),
  38. OutermostConditional(0), TerminateLandingPad(0), TerminateHandler(0),
  39. TrapBB(0) {
  40. CatchUndefined = getContext().getLangOptions().CatchUndefined;
  41. CGM.getCXXABI().getMangleContext().startNewFunction();
  42. }
  43. ASTContext &CodeGenFunction::getContext() const {
  44. return CGM.getContext();
  45. }
  46. const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  47. return CGM.getTypes().ConvertTypeForMem(T);
  48. }
  49. const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  50. return CGM.getTypes().ConvertType(T);
  51. }
  52. bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
  53. return T->isRecordType() || T->isArrayType() || T->isAnyComplexType() ||
  54. T->isObjCObjectType();
  55. }
  56. void CodeGenFunction::EmitReturnBlock() {
  57. // For cleanliness, we try to avoid emitting the return block for
  58. // simple cases.
  59. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  60. if (CurBB) {
  61. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  62. // We have a valid insert point, reuse it if it is empty or there are no
  63. // explicit jumps to the return block.
  64. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  65. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  66. delete ReturnBlock.getBlock();
  67. } else
  68. EmitBlock(ReturnBlock.getBlock());
  69. return;
  70. }
  71. // Otherwise, if the return block is the target of a single direct
  72. // branch then we can just put the code in that block instead. This
  73. // cleans up functions which started with a unified return block.
  74. if (ReturnBlock.getBlock()->hasOneUse()) {
  75. llvm::BranchInst *BI =
  76. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
  77. if (BI && BI->isUnconditional() &&
  78. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  79. // Reset insertion point and delete the branch.
  80. Builder.SetInsertPoint(BI->getParent());
  81. BI->eraseFromParent();
  82. delete ReturnBlock.getBlock();
  83. return;
  84. }
  85. }
  86. // FIXME: We are at an unreachable point, there is no reason to emit the block
  87. // unless it has uses. However, we still need a place to put the debug
  88. // region.end for now.
  89. EmitBlock(ReturnBlock.getBlock());
  90. }
  91. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  92. if (!BB) return;
  93. if (!BB->use_empty())
  94. return CGF.CurFn->getBasicBlockList().push_back(BB);
  95. delete BB;
  96. }
  97. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  98. assert(BreakContinueStack.empty() &&
  99. "mismatched push/pop in break/continue stack!");
  100. // Emit function epilog (to return).
  101. EmitReturnBlock();
  102. if (ShouldInstrumentFunction())
  103. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  104. // Emit debug descriptor for function end.
  105. if (CGDebugInfo *DI = getDebugInfo()) {
  106. DI->setLocation(EndLoc);
  107. DI->EmitFunctionEnd(Builder);
  108. }
  109. EmitFunctionEpilog(*CurFnInfo);
  110. EmitEndEHSpec(CurCodeDecl);
  111. assert(EHStack.empty() &&
  112. "did not remove all scopes from cleanup stack!");
  113. // If someone did an indirect goto, emit the indirect goto block at the end of
  114. // the function.
  115. if (IndirectBranch) {
  116. EmitBlock(IndirectBranch->getParent());
  117. Builder.ClearInsertionPoint();
  118. }
  119. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  120. llvm::Instruction *Ptr = AllocaInsertPt;
  121. AllocaInsertPt = 0;
  122. Ptr->eraseFromParent();
  123. // If someone took the address of a label but never did an indirect goto, we
  124. // made a zero entry PHI node, which is illegal, zap it now.
  125. if (IndirectBranch) {
  126. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  127. if (PN->getNumIncomingValues() == 0) {
  128. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  129. PN->eraseFromParent();
  130. }
  131. }
  132. EmitIfUsed(*this, RethrowBlock.getBlock());
  133. EmitIfUsed(*this, TerminateLandingPad);
  134. EmitIfUsed(*this, TerminateHandler);
  135. EmitIfUsed(*this, UnreachableBlock);
  136. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  137. EmitDeclMetadata();
  138. }
  139. /// ShouldInstrumentFunction - Return true if the current function should be
  140. /// instrumented with __cyg_profile_func_* calls
  141. bool CodeGenFunction::ShouldInstrumentFunction() {
  142. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  143. return false;
  144. if (CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  145. return false;
  146. return true;
  147. }
  148. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  149. /// instrumentation function with the current function and the call site, if
  150. /// function instrumentation is enabled.
  151. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  152. const llvm::PointerType *PointerTy;
  153. const llvm::FunctionType *FunctionTy;
  154. std::vector<const llvm::Type*> ProfileFuncArgs;
  155. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  156. PointerTy = Int8PtrTy;
  157. ProfileFuncArgs.push_back(PointerTy);
  158. ProfileFuncArgs.push_back(PointerTy);
  159. FunctionTy = llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
  160. ProfileFuncArgs, false);
  161. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  162. llvm::CallInst *CallSite = Builder.CreateCall(
  163. CGM.getIntrinsic(llvm::Intrinsic::returnaddress, 0, 0),
  164. llvm::ConstantInt::get(Int32Ty, 0),
  165. "callsite");
  166. Builder.CreateCall2(F,
  167. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  168. CallSite);
  169. }
  170. void CodeGenFunction::EmitMCountInstrumentation() {
  171. llvm::FunctionType *FTy =
  172. llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()), false);
  173. llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
  174. Target.getMCountName());
  175. Builder.CreateCall(MCountFn);
  176. }
  177. void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
  178. llvm::Function *Fn,
  179. const CGFunctionInfo &FnInfo,
  180. const FunctionArgList &Args,
  181. SourceLocation StartLoc) {
  182. const Decl *D = GD.getDecl();
  183. DidCallStackSave = false;
  184. CurCodeDecl = CurFuncDecl = D;
  185. FnRetTy = RetTy;
  186. CurFn = Fn;
  187. CurFnInfo = &FnInfo;
  188. assert(CurFn->isDeclaration() && "Function already has body?");
  189. // Pass inline keyword to optimizer if it appears explicitly on any
  190. // declaration.
  191. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  192. for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
  193. RE = FD->redecls_end(); RI != RE; ++RI)
  194. if (RI->isInlineSpecified()) {
  195. Fn->addFnAttr(llvm::Attribute::InlineHint);
  196. break;
  197. }
  198. if (getContext().getLangOptions().OpenCL) {
  199. // Add metadata for a kernel function.
  200. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  201. if (FD->hasAttr<OpenCLKernelAttr>()) {
  202. llvm::LLVMContext &Context = getLLVMContext();
  203. llvm::NamedMDNode *OpenCLMetadata =
  204. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  205. llvm::Value *Op = Fn;
  206. OpenCLMetadata->addOperand(llvm::MDNode::get(Context, &Op, 1));
  207. }
  208. }
  209. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  210. // Create a marker to make it easy to insert allocas into the entryblock
  211. // later. Don't create this with the builder, because we don't want it
  212. // folded.
  213. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  214. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  215. if (Builder.isNamePreserving())
  216. AllocaInsertPt->setName("allocapt");
  217. ReturnBlock = getJumpDestInCurrentScope("return");
  218. Builder.SetInsertPoint(EntryBB);
  219. // Emit subprogram debug descriptor.
  220. if (CGDebugInfo *DI = getDebugInfo()) {
  221. // FIXME: what is going on here and why does it ignore all these
  222. // interesting type properties?
  223. QualType FnType =
  224. getContext().getFunctionType(RetTy, 0, 0,
  225. FunctionProtoType::ExtProtoInfo());
  226. DI->setLocation(StartLoc);
  227. DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
  228. }
  229. if (ShouldInstrumentFunction())
  230. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  231. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  232. EmitMCountInstrumentation();
  233. if (RetTy->isVoidType()) {
  234. // Void type; nothing to return.
  235. ReturnValue = 0;
  236. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  237. hasAggregateLLVMType(CurFnInfo->getReturnType())) {
  238. // Indirect aggregate return; emit returned value directly into sret slot.
  239. // This reduces code size, and affects correctness in C++.
  240. ReturnValue = CurFn->arg_begin();
  241. } else {
  242. ReturnValue = CreateIRTemp(RetTy, "retval");
  243. }
  244. EmitStartEHSpec(CurCodeDecl);
  245. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  246. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
  247. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  248. // If any of the arguments have a variably modified type, make sure to
  249. // emit the type size.
  250. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  251. i != e; ++i) {
  252. QualType Ty = (*i)->getType();
  253. if (Ty->isVariablyModifiedType())
  254. EmitVLASize(Ty);
  255. }
  256. }
  257. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
  258. const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
  259. assert(FD->getBody());
  260. EmitStmt(FD->getBody());
  261. }
  262. /// Tries to mark the given function nounwind based on the
  263. /// non-existence of any throwing calls within it. We believe this is
  264. /// lightweight enough to do at -O0.
  265. static void TryMarkNoThrow(llvm::Function *F) {
  266. // LLVM treats 'nounwind' on a function as part of the type, so we
  267. // can't do this on functions that can be overwritten.
  268. if (F->mayBeOverridden()) return;
  269. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  270. for (llvm::BasicBlock::iterator
  271. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  272. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI))
  273. if (!Call->doesNotThrow())
  274. return;
  275. F->setDoesNotThrow(true);
  276. }
  277. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  278. const CGFunctionInfo &FnInfo) {
  279. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  280. // Check if we should generate debug info for this function.
  281. if (CGM.getModuleDebugInfo() && !FD->hasAttr<NoDebugAttr>())
  282. DebugInfo = CGM.getModuleDebugInfo();
  283. FunctionArgList Args;
  284. QualType ResTy = FD->getResultType();
  285. CurGD = GD;
  286. if (isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isInstance())
  287. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
  288. if (FD->getNumParams())
  289. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
  290. Args.push_back(FD->getParamDecl(i));
  291. SourceRange BodyRange;
  292. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  293. // Emit the standard function prologue.
  294. StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
  295. // Generate the body of the function.
  296. if (isa<CXXDestructorDecl>(FD))
  297. EmitDestructorBody(Args);
  298. else if (isa<CXXConstructorDecl>(FD))
  299. EmitConstructorBody(Args);
  300. else
  301. EmitFunctionBody(Args);
  302. // Emit the standard function epilogue.
  303. FinishFunction(BodyRange.getEnd());
  304. // If we haven't marked the function nothrow through other means, do
  305. // a quick pass now to see if we can.
  306. if (!CurFn->doesNotThrow())
  307. TryMarkNoThrow(CurFn);
  308. }
  309. /// ContainsLabel - Return true if the statement contains a label in it. If
  310. /// this statement is not executed normally, it not containing a label means
  311. /// that we can just remove the code.
  312. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  313. // Null statement, not a label!
  314. if (S == 0) return false;
  315. // If this is a label, we have to emit the code, consider something like:
  316. // if (0) { ... foo: bar(); } goto foo;
  317. //
  318. // TODO: If anyone cared, we could track __label__'s, since we know that you
  319. // can't jump to one from outside their declared region.
  320. if (isa<LabelStmt>(S))
  321. return true;
  322. // If this is a case/default statement, and we haven't seen a switch, we have
  323. // to emit the code.
  324. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  325. return true;
  326. // If this is a switch statement, we want to ignore cases below it.
  327. if (isa<SwitchStmt>(S))
  328. IgnoreCaseStmts = true;
  329. // Scan subexpressions for verboten labels.
  330. for (Stmt::const_child_range I = S->children(); I; ++I)
  331. if (ContainsLabel(*I, IgnoreCaseStmts))
  332. return true;
  333. return false;
  334. }
  335. /// containsBreak - Return true if the statement contains a break out of it.
  336. /// If the statement (recursively) contains a switch or loop with a break
  337. /// inside of it, this is fine.
  338. bool CodeGenFunction::containsBreak(const Stmt *S) {
  339. // Null statement, not a label!
  340. if (S == 0) return false;
  341. // If this is a switch or loop that defines its own break scope, then we can
  342. // include it and anything inside of it.
  343. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  344. isa<ForStmt>(S))
  345. return false;
  346. if (isa<BreakStmt>(S))
  347. return true;
  348. // Scan subexpressions for verboten breaks.
  349. for (Stmt::const_child_range I = S->children(); I; ++I)
  350. if (containsBreak(*I))
  351. return true;
  352. return false;
  353. }
  354. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  355. /// to a constant, or if it does but contains a label, return false. If it
  356. /// constant folds return true and set the boolean result in Result.
  357. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  358. bool &ResultBool) {
  359. llvm::APInt ResultInt;
  360. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  361. return false;
  362. ResultBool = ResultInt.getBoolValue();
  363. return true;
  364. }
  365. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  366. /// to a constant, or if it does but contains a label, return false. If it
  367. /// constant folds return true and set the folded value.
  368. bool CodeGenFunction::
  369. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &ResultInt) {
  370. // FIXME: Rename and handle conversion of other evaluatable things
  371. // to bool.
  372. Expr::EvalResult Result;
  373. if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
  374. Result.HasSideEffects)
  375. return false; // Not foldable, not integer or not fully evaluatable.
  376. if (CodeGenFunction::ContainsLabel(Cond))
  377. return false; // Contains a label.
  378. ResultInt = Result.Val.getInt();
  379. return true;
  380. }
  381. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  382. /// statement) to the specified blocks. Based on the condition, this might try
  383. /// to simplify the codegen of the conditional based on the branch.
  384. ///
  385. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  386. llvm::BasicBlock *TrueBlock,
  387. llvm::BasicBlock *FalseBlock) {
  388. if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
  389. return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
  390. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  391. // Handle X && Y in a condition.
  392. if (CondBOp->getOpcode() == BO_LAnd) {
  393. // If we have "1 && X", simplify the code. "0 && X" would have constant
  394. // folded if the case was simple enough.
  395. bool ConstantBool = false;
  396. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  397. ConstantBool) {
  398. // br(1 && X) -> br(X).
  399. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  400. }
  401. // If we have "X && 1", simplify the code to use an uncond branch.
  402. // "X && 0" would have been constant folded to 0.
  403. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  404. ConstantBool) {
  405. // br(X && 1) -> br(X).
  406. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  407. }
  408. // Emit the LHS as a conditional. If the LHS conditional is false, we
  409. // want to jump to the FalseBlock.
  410. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  411. ConditionalEvaluation eval(*this);
  412. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
  413. EmitBlock(LHSTrue);
  414. // Any temporaries created here are conditional.
  415. eval.begin(*this);
  416. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  417. eval.end(*this);
  418. return;
  419. }
  420. if (CondBOp->getOpcode() == BO_LOr) {
  421. // If we have "0 || X", simplify the code. "1 || X" would have constant
  422. // folded if the case was simple enough.
  423. bool ConstantBool = false;
  424. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  425. !ConstantBool) {
  426. // br(0 || X) -> br(X).
  427. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  428. }
  429. // If we have "X || 0", simplify the code to use an uncond branch.
  430. // "X || 1" would have been constant folded to 1.
  431. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  432. !ConstantBool) {
  433. // br(X || 0) -> br(X).
  434. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  435. }
  436. // Emit the LHS as a conditional. If the LHS conditional is true, we
  437. // want to jump to the TrueBlock.
  438. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  439. ConditionalEvaluation eval(*this);
  440. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
  441. EmitBlock(LHSFalse);
  442. // Any temporaries created here are conditional.
  443. eval.begin(*this);
  444. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  445. eval.end(*this);
  446. return;
  447. }
  448. }
  449. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  450. // br(!x, t, f) -> br(x, f, t)
  451. if (CondUOp->getOpcode() == UO_LNot)
  452. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
  453. }
  454. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  455. // Handle ?: operator.
  456. // Just ignore GNU ?: extension.
  457. if (CondOp->getLHS()) {
  458. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  459. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  460. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  461. ConditionalEvaluation cond(*this);
  462. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
  463. cond.begin(*this);
  464. EmitBlock(LHSBlock);
  465. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
  466. cond.end(*this);
  467. cond.begin(*this);
  468. EmitBlock(RHSBlock);
  469. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
  470. cond.end(*this);
  471. return;
  472. }
  473. }
  474. // Emit the code with the fully general case.
  475. llvm::Value *CondV = EvaluateExprAsBool(Cond);
  476. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  477. }
  478. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  479. /// specified stmt yet.
  480. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
  481. bool OmitOnError) {
  482. CGM.ErrorUnsupported(S, Type, OmitOnError);
  483. }
  484. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  485. /// variable-length array whose elements have a non-zero bit-pattern.
  486. ///
  487. /// \param src - a char* pointing to the bit-pattern for a single
  488. /// base element of the array
  489. /// \param sizeInChars - the total size of the VLA, in chars
  490. /// \param align - the total alignment of the VLA
  491. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  492. llvm::Value *dest, llvm::Value *src,
  493. llvm::Value *sizeInChars) {
  494. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  495. = CGF.getContext().getTypeInfoInChars(baseType);
  496. CGBuilderTy &Builder = CGF.Builder;
  497. llvm::Value *baseSizeInChars
  498. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  499. const llvm::Type *i8p = Builder.getInt8PtrTy();
  500. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  501. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  502. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  503. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  504. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  505. // Make a loop over the VLA. C99 guarantees that the VLA element
  506. // count must be nonzero.
  507. CGF.EmitBlock(loopBB);
  508. llvm::PHINode *cur = Builder.CreatePHI(i8p, "vla.cur");
  509. cur->reserveOperandSpace(2);
  510. cur->addIncoming(begin, originBB);
  511. // memcpy the individual element bit-pattern.
  512. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  513. baseSizeAndAlign.second.getQuantity(),
  514. /*volatile*/ false);
  515. // Go to the next element.
  516. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
  517. // Leave if that's the end of the VLA.
  518. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  519. Builder.CreateCondBr(done, contBB, loopBB);
  520. cur->addIncoming(next, loopBB);
  521. CGF.EmitBlock(contBB);
  522. }
  523. void
  524. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  525. // Ignore empty classes in C++.
  526. if (getContext().getLangOptions().CPlusPlus) {
  527. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  528. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  529. return;
  530. }
  531. }
  532. // Cast the dest ptr to the appropriate i8 pointer type.
  533. unsigned DestAS =
  534. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  535. const llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  536. if (DestPtr->getType() != BP)
  537. DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
  538. // Get size and alignment info for this aggregate.
  539. std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
  540. uint64_t Size = TypeInfo.first / 8;
  541. unsigned Align = TypeInfo.second / 8;
  542. llvm::Value *SizeVal;
  543. const VariableArrayType *vla;
  544. // Don't bother emitting a zero-byte memset.
  545. if (Size == 0) {
  546. // But note that getTypeInfo returns 0 for a VLA.
  547. if (const VariableArrayType *vlaType =
  548. dyn_cast_or_null<VariableArrayType>(
  549. getContext().getAsArrayType(Ty))) {
  550. SizeVal = GetVLASize(vlaType);
  551. vla = vlaType;
  552. } else {
  553. return;
  554. }
  555. } else {
  556. SizeVal = llvm::ConstantInt::get(IntPtrTy, Size);
  557. vla = 0;
  558. }
  559. // If the type contains a pointer to data member we can't memset it to zero.
  560. // Instead, create a null constant and copy it to the destination.
  561. // TODO: there are other patterns besides zero that we can usefully memset,
  562. // like -1, which happens to be the pattern used by member-pointers.
  563. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  564. // For a VLA, emit a single element, then splat that over the VLA.
  565. if (vla) Ty = getContext().getBaseElementType(vla);
  566. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  567. llvm::GlobalVariable *NullVariable =
  568. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  569. /*isConstant=*/true,
  570. llvm::GlobalVariable::PrivateLinkage,
  571. NullConstant, llvm::Twine());
  572. llvm::Value *SrcPtr =
  573. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  574. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  575. // Get and call the appropriate llvm.memcpy overload.
  576. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align, false);
  577. return;
  578. }
  579. // Otherwise, just memset the whole thing to zero. This is legal
  580. // because in LLVM, all default initializers (other than the ones we just
  581. // handled above) are guaranteed to have a bit pattern of all zeros.
  582. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, Align, false);
  583. }
  584. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  585. // Make sure that there is a block for the indirect goto.
  586. if (IndirectBranch == 0)
  587. GetIndirectGotoBlock();
  588. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  589. // Make sure the indirect branch includes all of the address-taken blocks.
  590. IndirectBranch->addDestination(BB);
  591. return llvm::BlockAddress::get(CurFn, BB);
  592. }
  593. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  594. // If we already made the indirect branch for indirect goto, return its block.
  595. if (IndirectBranch) return IndirectBranch->getParent();
  596. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  597. // Create the PHI node that indirect gotos will add entries to.
  598. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, "indirect.goto.dest");
  599. // Create the indirect branch instruction.
  600. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  601. return IndirectBranch->getParent();
  602. }
  603. llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
  604. llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
  605. assert(SizeEntry && "Did not emit size for type");
  606. return SizeEntry;
  607. }
  608. llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
  609. assert(Ty->isVariablyModifiedType() &&
  610. "Must pass variably modified type to EmitVLASizes!");
  611. EnsureInsertPoint();
  612. if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
  613. // unknown size indication requires no size computation.
  614. if (!VAT->getSizeExpr())
  615. return 0;
  616. llvm::Value *&SizeEntry = VLASizeMap[VAT->getSizeExpr()];
  617. if (!SizeEntry) {
  618. const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
  619. // Get the element size;
  620. QualType ElemTy = VAT->getElementType();
  621. llvm::Value *ElemSize;
  622. if (ElemTy->isVariableArrayType())
  623. ElemSize = EmitVLASize(ElemTy);
  624. else
  625. ElemSize = llvm::ConstantInt::get(SizeTy,
  626. getContext().getTypeSizeInChars(ElemTy).getQuantity());
  627. llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
  628. NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
  629. SizeEntry = Builder.CreateMul(ElemSize, NumElements);
  630. }
  631. return SizeEntry;
  632. }
  633. if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  634. EmitVLASize(AT->getElementType());
  635. return 0;
  636. }
  637. if (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
  638. EmitVLASize(PT->getInnerType());
  639. return 0;
  640. }
  641. const PointerType *PT = Ty->getAs<PointerType>();
  642. assert(PT && "unknown VM type!");
  643. EmitVLASize(PT->getPointeeType());
  644. return 0;
  645. }
  646. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  647. if (getContext().getBuiltinVaListType()->isArrayType())
  648. return EmitScalarExpr(E);
  649. return EmitLValue(E).getAddress();
  650. }
  651. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  652. llvm::Constant *Init) {
  653. assert (Init && "Invalid DeclRefExpr initializer!");
  654. if (CGDebugInfo *Dbg = getDebugInfo())
  655. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  656. }
  657. CodeGenFunction::PeepholeProtection
  658. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  659. // At the moment, the only aggressive peephole we do in IR gen
  660. // is trunc(zext) folding, but if we add more, we can easily
  661. // extend this protection.
  662. if (!rvalue.isScalar()) return PeepholeProtection();
  663. llvm::Value *value = rvalue.getScalarVal();
  664. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  665. // Just make an extra bitcast.
  666. assert(HaveInsertPoint());
  667. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  668. Builder.GetInsertBlock());
  669. PeepholeProtection protection;
  670. protection.Inst = inst;
  671. return protection;
  672. }
  673. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  674. if (!protection.Inst) return;
  675. // In theory, we could try to duplicate the peepholes now, but whatever.
  676. protection.Inst->eraseFromParent();
  677. }