CodeGenFunction.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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 "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGDebugInfo.h"
  17. #include "CodeGenModule.h"
  18. #include "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/Basic/OpenCL.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/CodeGen/CGFunctionInfo.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/Intrinsics.h"
  29. #include "llvm/IR/MDBuilder.h"
  30. #include "llvm/IR/Operator.h"
  31. using namespace clang;
  32. using namespace CodeGen;
  33. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  34. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  35. Builder(cgm.getModule().getContext()), CapturedStmtInfo(0),
  36. SanitizePerformTypeCheck(CGM.getSanOpts().Null |
  37. CGM.getSanOpts().Alignment |
  38. CGM.getSanOpts().ObjectSize |
  39. CGM.getSanOpts().Vptr),
  40. SanOpts(&CGM.getSanOpts()), AutoreleaseResult(false), BlockInfo(0),
  41. BlockPointer(0), LambdaThisCaptureField(0), NormalCleanupDest(0),
  42. NextCleanupDestIndex(1), FirstBlockInfo(0), EHResumeBlock(0),
  43. ExceptionSlot(0), EHSelectorSlot(0), DebugInfo(CGM.getModuleDebugInfo()),
  44. DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(0),
  45. SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0), NumReturnExprs(0),
  46. NumSimpleReturnExprs(0), CXXABIThisDecl(0), CXXABIThisValue(0),
  47. CXXThisValue(0), CXXDefaultInitExprThis(0),
  48. CXXStructorImplicitParamDecl(0), CXXStructorImplicitParamValue(0),
  49. OutermostConditional(0), CurLexicalScope(0), TerminateLandingPad(0),
  50. TerminateHandler(0), TrapBB(0) {
  51. if (!suppressNewContext)
  52. CGM.getCXXABI().getMangleContext().startNewFunction();
  53. llvm::FastMathFlags FMF;
  54. if (CGM.getLangOpts().FastMath)
  55. FMF.setUnsafeAlgebra();
  56. if (CGM.getLangOpts().FiniteMathOnly) {
  57. FMF.setNoNaNs();
  58. FMF.setNoInfs();
  59. }
  60. Builder.SetFastMathFlags(FMF);
  61. }
  62. CodeGenFunction::~CodeGenFunction() {
  63. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  64. // If there are any unclaimed block infos, go ahead and destroy them
  65. // now. This can happen if IR-gen gets clever and skips evaluating
  66. // something.
  67. if (FirstBlockInfo)
  68. destroyBlockInfos(FirstBlockInfo);
  69. }
  70. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  71. return CGM.getTypes().ConvertTypeForMem(T);
  72. }
  73. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  74. return CGM.getTypes().ConvertType(T);
  75. }
  76. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  77. type = type.getCanonicalType();
  78. while (true) {
  79. switch (type->getTypeClass()) {
  80. #define TYPE(name, parent)
  81. #define ABSTRACT_TYPE(name, parent)
  82. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  83. #define DEPENDENT_TYPE(name, parent) case Type::name:
  84. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  85. #include "clang/AST/TypeNodes.def"
  86. llvm_unreachable("non-canonical or dependent type in IR-generation");
  87. case Type::Auto:
  88. llvm_unreachable("undeduced auto type in IR-generation");
  89. // Various scalar types.
  90. case Type::Builtin:
  91. case Type::Pointer:
  92. case Type::BlockPointer:
  93. case Type::LValueReference:
  94. case Type::RValueReference:
  95. case Type::MemberPointer:
  96. case Type::Vector:
  97. case Type::ExtVector:
  98. case Type::FunctionProto:
  99. case Type::FunctionNoProto:
  100. case Type::Enum:
  101. case Type::ObjCObjectPointer:
  102. return TEK_Scalar;
  103. // Complexes.
  104. case Type::Complex:
  105. return TEK_Complex;
  106. // Arrays, records, and Objective-C objects.
  107. case Type::ConstantArray:
  108. case Type::IncompleteArray:
  109. case Type::VariableArray:
  110. case Type::Record:
  111. case Type::ObjCObject:
  112. case Type::ObjCInterface:
  113. return TEK_Aggregate;
  114. // We operate on atomic values according to their underlying type.
  115. case Type::Atomic:
  116. type = cast<AtomicType>(type)->getValueType();
  117. continue;
  118. }
  119. llvm_unreachable("unknown type kind!");
  120. }
  121. }
  122. void CodeGenFunction::EmitReturnBlock() {
  123. // For cleanliness, we try to avoid emitting the return block for
  124. // simple cases.
  125. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  126. if (CurBB) {
  127. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  128. // We have a valid insert point, reuse it if it is empty or there are no
  129. // explicit jumps to the return block.
  130. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  131. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  132. delete ReturnBlock.getBlock();
  133. } else
  134. EmitBlock(ReturnBlock.getBlock());
  135. return;
  136. }
  137. // Otherwise, if the return block is the target of a single direct
  138. // branch then we can just put the code in that block instead. This
  139. // cleans up functions which started with a unified return block.
  140. if (ReturnBlock.getBlock()->hasOneUse()) {
  141. llvm::BranchInst *BI =
  142. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
  143. if (BI && BI->isUnconditional() &&
  144. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  145. // Reset insertion point, including debug location, and delete the
  146. // branch. This is really subtle and only works because the next change
  147. // in location will hit the caching in CGDebugInfo::EmitLocation and not
  148. // override this.
  149. Builder.SetCurrentDebugLocation(BI->getDebugLoc());
  150. Builder.SetInsertPoint(BI->getParent());
  151. BI->eraseFromParent();
  152. delete ReturnBlock.getBlock();
  153. return;
  154. }
  155. }
  156. // FIXME: We are at an unreachable point, there is no reason to emit the block
  157. // unless it has uses. However, we still need a place to put the debug
  158. // region.end for now.
  159. EmitBlock(ReturnBlock.getBlock());
  160. }
  161. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  162. if (!BB) return;
  163. if (!BB->use_empty())
  164. return CGF.CurFn->getBasicBlockList().push_back(BB);
  165. delete BB;
  166. }
  167. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  168. assert(BreakContinueStack.empty() &&
  169. "mismatched push/pop in break/continue stack!");
  170. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  171. && NumSimpleReturnExprs == NumReturnExprs
  172. && ReturnBlock.getBlock()->use_empty();
  173. // Usually the return expression is evaluated before the cleanup
  174. // code. If the function contains only a simple return statement,
  175. // such as a constant, the location before the cleanup code becomes
  176. // the last useful breakpoint in the function, because the simple
  177. // return expression will be evaluated after the cleanup code. To be
  178. // safe, set the debug location for cleanup code to the location of
  179. // the return statement. Otherwise the cleanup code should be at the
  180. // end of the function's lexical scope.
  181. //
  182. // If there are multiple branches to the return block, the branch
  183. // instructions will get the location of the return statements and
  184. // all will be fine.
  185. if (CGDebugInfo *DI = getDebugInfo()) {
  186. if (OnlySimpleReturnStmts)
  187. DI->EmitLocation(Builder, LastStopPoint);
  188. else
  189. DI->EmitLocation(Builder, EndLoc);
  190. }
  191. // Pop any cleanups that might have been associated with the
  192. // parameters. Do this in whatever block we're currently in; it's
  193. // important to do this before we enter the return block or return
  194. // edges will be *really* confused.
  195. bool EmitRetDbgLoc = true;
  196. if (EHStack.stable_begin() != PrologueCleanupDepth) {
  197. PopCleanupBlocks(PrologueCleanupDepth);
  198. // Make sure the line table doesn't jump back into the body for
  199. // the ret after it's been at EndLoc.
  200. EmitRetDbgLoc = false;
  201. if (CGDebugInfo *DI = getDebugInfo())
  202. if (OnlySimpleReturnStmts)
  203. DI->EmitLocation(Builder, EndLoc);
  204. }
  205. // Emit function epilog (to return).
  206. EmitReturnBlock();
  207. if (ShouldInstrumentFunction())
  208. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  209. // Emit debug descriptor for function end.
  210. if (CGDebugInfo *DI = getDebugInfo()) {
  211. DI->EmitFunctionEnd(Builder);
  212. }
  213. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc);
  214. EmitEndEHSpec(CurCodeDecl);
  215. assert(EHStack.empty() &&
  216. "did not remove all scopes from cleanup stack!");
  217. // If someone did an indirect goto, emit the indirect goto block at the end of
  218. // the function.
  219. if (IndirectBranch) {
  220. EmitBlock(IndirectBranch->getParent());
  221. Builder.ClearInsertionPoint();
  222. }
  223. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  224. llvm::Instruction *Ptr = AllocaInsertPt;
  225. AllocaInsertPt = 0;
  226. Ptr->eraseFromParent();
  227. // If someone took the address of a label but never did an indirect goto, we
  228. // made a zero entry PHI node, which is illegal, zap it now.
  229. if (IndirectBranch) {
  230. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  231. if (PN->getNumIncomingValues() == 0) {
  232. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  233. PN->eraseFromParent();
  234. }
  235. }
  236. EmitIfUsed(*this, EHResumeBlock);
  237. EmitIfUsed(*this, TerminateLandingPad);
  238. EmitIfUsed(*this, TerminateHandler);
  239. EmitIfUsed(*this, UnreachableBlock);
  240. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  241. EmitDeclMetadata();
  242. }
  243. /// ShouldInstrumentFunction - Return true if the current function should be
  244. /// instrumented with __cyg_profile_func_* calls
  245. bool CodeGenFunction::ShouldInstrumentFunction() {
  246. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  247. return false;
  248. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  249. return false;
  250. return true;
  251. }
  252. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  253. /// instrumentation function with the current function and the call site, if
  254. /// function instrumentation is enabled.
  255. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  256. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  257. llvm::PointerType *PointerTy = Int8PtrTy;
  258. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  259. llvm::FunctionType *FunctionTy =
  260. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  261. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  262. llvm::CallInst *CallSite = Builder.CreateCall(
  263. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  264. llvm::ConstantInt::get(Int32Ty, 0),
  265. "callsite");
  266. llvm::Value *args[] = {
  267. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  268. CallSite
  269. };
  270. EmitNounwindRuntimeCall(F, args);
  271. }
  272. void CodeGenFunction::EmitMCountInstrumentation() {
  273. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  274. llvm::Constant *MCountFn =
  275. CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
  276. EmitNounwindRuntimeCall(MCountFn);
  277. }
  278. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  279. // information in the program executable. The argument information stored
  280. // includes the argument name, its type, the address and access qualifiers used.
  281. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  282. CodeGenModule &CGM,llvm::LLVMContext &Context,
  283. SmallVector <llvm::Value*, 5> &kernelMDArgs,
  284. CGBuilderTy& Builder, ASTContext &ASTCtx) {
  285. // Create MDNodes that represent the kernel arg metadata.
  286. // Each MDNode is a list in the form of "key", N number of values which is
  287. // the same number of values as their are kernel arguments.
  288. // MDNode for the kernel argument address space qualifiers.
  289. SmallVector<llvm::Value*, 8> addressQuals;
  290. addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
  291. // MDNode for the kernel argument access qualifiers (images only).
  292. SmallVector<llvm::Value*, 8> accessQuals;
  293. accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
  294. // MDNode for the kernel argument type names.
  295. SmallVector<llvm::Value*, 8> argTypeNames;
  296. argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
  297. // MDNode for the kernel argument type qualifiers.
  298. SmallVector<llvm::Value*, 8> argTypeQuals;
  299. argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
  300. // MDNode for the kernel argument names.
  301. SmallVector<llvm::Value*, 8> argNames;
  302. argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
  303. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  304. const ParmVarDecl *parm = FD->getParamDecl(i);
  305. QualType ty = parm->getType();
  306. std::string typeQuals;
  307. if (ty->isPointerType()) {
  308. QualType pointeeTy = ty->getPointeeType();
  309. // Get address qualifier.
  310. addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
  311. pointeeTy.getAddressSpace())));
  312. // Get argument type name.
  313. std::string typeName = pointeeTy.getUnqualifiedType().getAsString() + "*";
  314. // Turn "unsigned type" to "utype"
  315. std::string::size_type pos = typeName.find("unsigned");
  316. if (pos != std::string::npos)
  317. typeName.erase(pos+1, 8);
  318. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  319. // Get argument type qualifiers:
  320. if (ty.isRestrictQualified())
  321. typeQuals = "restrict";
  322. if (pointeeTy.isConstQualified() ||
  323. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  324. typeQuals += typeQuals.empty() ? "const" : " const";
  325. if (pointeeTy.isVolatileQualified())
  326. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  327. } else {
  328. addressQuals.push_back(Builder.getInt32(0));
  329. // Get argument type name.
  330. std::string typeName = ty.getUnqualifiedType().getAsString();
  331. // Turn "unsigned type" to "utype"
  332. std::string::size_type pos = typeName.find("unsigned");
  333. if (pos != std::string::npos)
  334. typeName.erase(pos+1, 8);
  335. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  336. // Get argument type qualifiers:
  337. if (ty.isConstQualified())
  338. typeQuals = "const";
  339. if (ty.isVolatileQualified())
  340. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  341. }
  342. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  343. // Get image access qualifier:
  344. if (ty->isImageType()) {
  345. if (parm->hasAttr<OpenCLImageAccessAttr>() &&
  346. parm->getAttr<OpenCLImageAccessAttr>()->getAccess() == CLIA_write_only)
  347. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  348. else
  349. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  350. } else
  351. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  352. // Get argument name.
  353. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  354. }
  355. kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
  356. kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
  357. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
  358. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
  359. kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
  360. }
  361. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  362. llvm::Function *Fn)
  363. {
  364. if (!FD->hasAttr<OpenCLKernelAttr>())
  365. return;
  366. llvm::LLVMContext &Context = getLLVMContext();
  367. SmallVector <llvm::Value*, 5> kernelMDArgs;
  368. kernelMDArgs.push_back(Fn);
  369. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  370. GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
  371. Builder, getContext());
  372. if (FD->hasAttr<VecTypeHintAttr>()) {
  373. VecTypeHintAttr *attr = FD->getAttr<VecTypeHintAttr>();
  374. QualType hintQTy = attr->getTypeHint();
  375. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  376. bool isSignedInteger =
  377. hintQTy->isSignedIntegerType() ||
  378. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  379. llvm::Value *attrMDArgs[] = {
  380. llvm::MDString::get(Context, "vec_type_hint"),
  381. llvm::UndefValue::get(CGM.getTypes().ConvertType(attr->getTypeHint())),
  382. llvm::ConstantInt::get(
  383. llvm::IntegerType::get(Context, 32),
  384. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
  385. };
  386. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  387. }
  388. if (FD->hasAttr<WorkGroupSizeHintAttr>()) {
  389. WorkGroupSizeHintAttr *attr = FD->getAttr<WorkGroupSizeHintAttr>();
  390. llvm::Value *attrMDArgs[] = {
  391. llvm::MDString::get(Context, "work_group_size_hint"),
  392. Builder.getInt32(attr->getXDim()),
  393. Builder.getInt32(attr->getYDim()),
  394. Builder.getInt32(attr->getZDim())
  395. };
  396. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  397. }
  398. if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
  399. ReqdWorkGroupSizeAttr *attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
  400. llvm::Value *attrMDArgs[] = {
  401. llvm::MDString::get(Context, "reqd_work_group_size"),
  402. Builder.getInt32(attr->getXDim()),
  403. Builder.getInt32(attr->getYDim()),
  404. Builder.getInt32(attr->getZDim())
  405. };
  406. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  407. }
  408. llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
  409. llvm::NamedMDNode *OpenCLKernelMetadata =
  410. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  411. OpenCLKernelMetadata->addOperand(kernelMDNode);
  412. }
  413. void CodeGenFunction::StartFunction(GlobalDecl GD,
  414. QualType RetTy,
  415. llvm::Function *Fn,
  416. const CGFunctionInfo &FnInfo,
  417. const FunctionArgList &Args,
  418. SourceLocation StartLoc) {
  419. const Decl *D = GD.getDecl();
  420. DidCallStackSave = false;
  421. CurCodeDecl = D;
  422. CurFuncDecl = (D ? D->getNonClosureContext() : 0);
  423. FnRetTy = RetTy;
  424. CurFn = Fn;
  425. CurFnInfo = &FnInfo;
  426. assert(CurFn->isDeclaration() && "Function already has body?");
  427. if (CGM.getSanitizerBlacklist().isIn(*Fn)) {
  428. SanOpts = &SanitizerOptions::Disabled;
  429. SanitizePerformTypeCheck = false;
  430. }
  431. // Pass inline keyword to optimizer if it appears explicitly on any
  432. // declaration.
  433. if (!CGM.getCodeGenOpts().NoInline)
  434. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  435. for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
  436. RE = FD->redecls_end(); RI != RE; ++RI)
  437. if (RI->isInlineSpecified()) {
  438. Fn->addFnAttr(llvm::Attribute::InlineHint);
  439. break;
  440. }
  441. if (getLangOpts().OpenCL) {
  442. // Add metadata for a kernel function.
  443. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  444. EmitOpenCLKernelMetadata(FD, Fn);
  445. }
  446. // If we are checking function types, emit a function type signature as
  447. // prefix data.
  448. if (getLangOpts().CPlusPlus && SanOpts->Function) {
  449. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
  450. if (llvm::Constant *PrefixSig =
  451. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  452. llvm::Constant *FTRTTIConst =
  453. CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true);
  454. llvm::Constant *PrefixStructElems[] = { PrefixSig, FTRTTIConst };
  455. llvm::Constant *PrefixStructConst =
  456. llvm::ConstantStruct::getAnon(PrefixStructElems, /*Packed=*/true);
  457. Fn->setPrefixData(PrefixStructConst);
  458. }
  459. }
  460. }
  461. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  462. // Create a marker to make it easy to insert allocas into the entryblock
  463. // later. Don't create this with the builder, because we don't want it
  464. // folded.
  465. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  466. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  467. if (Builder.isNamePreserving())
  468. AllocaInsertPt->setName("allocapt");
  469. ReturnBlock = getJumpDestInCurrentScope("return");
  470. Builder.SetInsertPoint(EntryBB);
  471. // Emit subprogram debug descriptor.
  472. if (CGDebugInfo *DI = getDebugInfo()) {
  473. SmallVector<QualType, 16> ArgTypes;
  474. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  475. i != e; ++i) {
  476. ArgTypes.push_back((*i)->getType());
  477. }
  478. QualType FnType =
  479. getContext().getFunctionType(RetTy, ArgTypes,
  480. FunctionProtoType::ExtProtoInfo());
  481. DI->setLocation(StartLoc);
  482. DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
  483. }
  484. if (ShouldInstrumentFunction())
  485. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  486. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  487. EmitMCountInstrumentation();
  488. if (RetTy->isVoidType()) {
  489. // Void type; nothing to return.
  490. ReturnValue = 0;
  491. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  492. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  493. // Indirect aggregate return; emit returned value directly into sret slot.
  494. // This reduces code size, and affects correctness in C++.
  495. ReturnValue = CurFn->arg_begin();
  496. } else {
  497. ReturnValue = CreateIRTemp(RetTy, "retval");
  498. // Tell the epilog emitter to autorelease the result. We do this
  499. // now so that various specialized functions can suppress it
  500. // during their IR-generation.
  501. if (getLangOpts().ObjCAutoRefCount &&
  502. !CurFnInfo->isReturnsRetained() &&
  503. RetTy->isObjCRetainableType())
  504. AutoreleaseResult = true;
  505. }
  506. EmitStartEHSpec(CurCodeDecl);
  507. PrologueCleanupDepth = EHStack.stable_begin();
  508. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  509. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  510. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  511. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  512. if (MD->getParent()->isLambda() &&
  513. MD->getOverloadedOperator() == OO_Call) {
  514. // We're in a lambda; figure out the captures.
  515. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  516. LambdaThisCaptureField);
  517. if (LambdaThisCaptureField) {
  518. // If this lambda captures this, load it.
  519. LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  520. CXXThisValue = EmitLoadOfLValue(ThisLValue,
  521. SourceLocation()).getScalarVal();
  522. }
  523. } else {
  524. // Not in a lambda; just use 'this' from the method.
  525. // FIXME: Should we generate a new load for each use of 'this'? The
  526. // fast register allocator would be happier...
  527. CXXThisValue = CXXABIThisValue;
  528. }
  529. }
  530. // If any of the arguments have a variably modified type, make sure to
  531. // emit the type size.
  532. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  533. i != e; ++i) {
  534. const VarDecl *VD = *i;
  535. // Dig out the type as written from ParmVarDecls; it's unclear whether
  536. // the standard (C99 6.9.1p10) requires this, but we're following the
  537. // precedent set by gcc.
  538. QualType Ty;
  539. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  540. Ty = PVD->getOriginalType();
  541. else
  542. Ty = VD->getType();
  543. if (Ty->isVariablyModifiedType())
  544. EmitVariablyModifiedType(Ty);
  545. }
  546. // Emit a location at the end of the prologue.
  547. if (CGDebugInfo *DI = getDebugInfo())
  548. DI->EmitLocation(Builder, StartLoc);
  549. }
  550. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args,
  551. const Stmt *Body) {
  552. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
  553. EmitCompoundStmtWithoutScope(*S);
  554. else
  555. EmitStmt(Body);
  556. }
  557. /// Tries to mark the given function nounwind based on the
  558. /// non-existence of any throwing calls within it. We believe this is
  559. /// lightweight enough to do at -O0.
  560. static void TryMarkNoThrow(llvm::Function *F) {
  561. // LLVM treats 'nounwind' on a function as part of the type, so we
  562. // can't do this on functions that can be overwritten.
  563. if (F->mayBeOverridden()) return;
  564. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  565. for (llvm::BasicBlock::iterator
  566. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  567. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  568. if (!Call->doesNotThrow())
  569. return;
  570. } else if (isa<llvm::ResumeInst>(&*BI)) {
  571. return;
  572. }
  573. F->setDoesNotThrow();
  574. }
  575. static void EmitSizedDeallocationFunction(CodeGenFunction &CGF,
  576. const FunctionDecl *UnsizedDealloc) {
  577. // This is a weak discardable definition of the sized deallocation function.
  578. CGF.CurFn->setLinkage(llvm::Function::LinkOnceAnyLinkage);
  579. // Call the unsized deallocation function and forward the first argument
  580. // unchanged.
  581. llvm::Constant *Unsized = CGF.CGM.GetAddrOfFunction(UnsizedDealloc);
  582. CGF.Builder.CreateCall(Unsized, &*CGF.CurFn->arg_begin());
  583. }
  584. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  585. const CGFunctionInfo &FnInfo) {
  586. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  587. // Check if we should generate debug info for this function.
  588. if (FD->hasAttr<NoDebugAttr>())
  589. DebugInfo = NULL; // disable debug info indefinitely for this function
  590. FunctionArgList Args;
  591. QualType ResTy = FD->getResultType();
  592. CurGD = GD;
  593. const CXXMethodDecl *MD;
  594. if ((MD = dyn_cast<CXXMethodDecl>(FD)) && MD->isInstance()) {
  595. if (CGM.getCXXABI().HasThisReturn(GD))
  596. ResTy = MD->getThisType(getContext());
  597. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
  598. }
  599. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
  600. Args.push_back(FD->getParamDecl(i));
  601. SourceRange BodyRange;
  602. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  603. CurEHLocation = BodyRange.getEnd();
  604. // Emit the standard function prologue.
  605. StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
  606. // Generate the body of the function.
  607. if (isa<CXXDestructorDecl>(FD))
  608. EmitDestructorBody(Args);
  609. else if (isa<CXXConstructorDecl>(FD))
  610. EmitConstructorBody(Args);
  611. else if (getLangOpts().CUDA &&
  612. !CGM.getCodeGenOpts().CUDAIsDevice &&
  613. FD->hasAttr<CUDAGlobalAttr>())
  614. CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
  615. else if (isa<CXXConversionDecl>(FD) &&
  616. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  617. // The lambda conversion to block pointer is special; the semantics can't be
  618. // expressed in the AST, so IRGen needs to special-case it.
  619. EmitLambdaToBlockPointerBody(Args);
  620. } else if (isa<CXXMethodDecl>(FD) &&
  621. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  622. // The lambda static invoker function is special, because it forwards or
  623. // clones the body of the function call operator (but is actually static).
  624. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  625. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  626. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  627. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  628. // Implicit copy-assignment gets the same special treatment as implicit
  629. // copy-constructors.
  630. emitImplicitAssignmentOperatorBody(Args);
  631. } else if (Stmt *Body = FD->getBody()) {
  632. EmitFunctionBody(Args, Body);
  633. } else if (FunctionDecl *UnsizedDealloc =
  634. FD->getCorrespondingUnsizedGlobalDeallocationFunction()) {
  635. // Global sized deallocation functions get an implicit weak definition if
  636. // they don't have an explicit definition.
  637. EmitSizedDeallocationFunction(*this, UnsizedDealloc);
  638. } else
  639. llvm_unreachable("no definition for emitted function");
  640. // C++11 [stmt.return]p2:
  641. // Flowing off the end of a function [...] results in undefined behavior in
  642. // a value-returning function.
  643. // C11 6.9.1p12:
  644. // If the '}' that terminates a function is reached, and the value of the
  645. // function call is used by the caller, the behavior is undefined.
  646. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() &&
  647. !FD->getResultType()->isVoidType() && Builder.GetInsertBlock()) {
  648. if (SanOpts->Return)
  649. EmitCheck(Builder.getFalse(), "missing_return",
  650. EmitCheckSourceLocation(FD->getLocation()),
  651. ArrayRef<llvm::Value *>(), CRK_Unrecoverable);
  652. else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  653. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
  654. Builder.CreateUnreachable();
  655. Builder.ClearInsertionPoint();
  656. }
  657. // Emit the standard function epilogue.
  658. FinishFunction(BodyRange.getEnd());
  659. // If we haven't marked the function nothrow through other means, do
  660. // a quick pass now to see if we can.
  661. if (!CurFn->doesNotThrow())
  662. TryMarkNoThrow(CurFn);
  663. }
  664. /// ContainsLabel - Return true if the statement contains a label in it. If
  665. /// this statement is not executed normally, it not containing a label means
  666. /// that we can just remove the code.
  667. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  668. // Null statement, not a label!
  669. if (S == 0) return false;
  670. // If this is a label, we have to emit the code, consider something like:
  671. // if (0) { ... foo: bar(); } goto foo;
  672. //
  673. // TODO: If anyone cared, we could track __label__'s, since we know that you
  674. // can't jump to one from outside their declared region.
  675. if (isa<LabelStmt>(S))
  676. return true;
  677. // If this is a case/default statement, and we haven't seen a switch, we have
  678. // to emit the code.
  679. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  680. return true;
  681. // If this is a switch statement, we want to ignore cases below it.
  682. if (isa<SwitchStmt>(S))
  683. IgnoreCaseStmts = true;
  684. // Scan subexpressions for verboten labels.
  685. for (Stmt::const_child_range I = S->children(); I; ++I)
  686. if (ContainsLabel(*I, IgnoreCaseStmts))
  687. return true;
  688. return false;
  689. }
  690. /// containsBreak - Return true if the statement contains a break out of it.
  691. /// If the statement (recursively) contains a switch or loop with a break
  692. /// inside of it, this is fine.
  693. bool CodeGenFunction::containsBreak(const Stmt *S) {
  694. // Null statement, not a label!
  695. if (S == 0) return false;
  696. // If this is a switch or loop that defines its own break scope, then we can
  697. // include it and anything inside of it.
  698. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  699. isa<ForStmt>(S))
  700. return false;
  701. if (isa<BreakStmt>(S))
  702. return true;
  703. // Scan subexpressions for verboten breaks.
  704. for (Stmt::const_child_range I = S->children(); I; ++I)
  705. if (containsBreak(*I))
  706. return true;
  707. return false;
  708. }
  709. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  710. /// to a constant, or if it does but contains a label, return false. If it
  711. /// constant folds return true and set the boolean result in Result.
  712. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  713. bool &ResultBool) {
  714. llvm::APSInt ResultInt;
  715. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  716. return false;
  717. ResultBool = ResultInt.getBoolValue();
  718. return true;
  719. }
  720. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  721. /// to a constant, or if it does but contains a label, return false. If it
  722. /// constant folds return true and set the folded value.
  723. bool CodeGenFunction::
  724. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
  725. // FIXME: Rename and handle conversion of other evaluatable things
  726. // to bool.
  727. llvm::APSInt Int;
  728. if (!Cond->EvaluateAsInt(Int, getContext()))
  729. return false; // Not foldable, not integer or not fully evaluatable.
  730. if (CodeGenFunction::ContainsLabel(Cond))
  731. return false; // Contains a label.
  732. ResultInt = Int;
  733. return true;
  734. }
  735. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  736. /// statement) to the specified blocks. Based on the condition, this might try
  737. /// to simplify the codegen of the conditional based on the branch.
  738. ///
  739. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  740. llvm::BasicBlock *TrueBlock,
  741. llvm::BasicBlock *FalseBlock) {
  742. Cond = Cond->IgnoreParens();
  743. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  744. // Handle X && Y in a condition.
  745. if (CondBOp->getOpcode() == BO_LAnd) {
  746. // If we have "1 && X", simplify the code. "0 && X" would have constant
  747. // folded if the case was simple enough.
  748. bool ConstantBool = false;
  749. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  750. ConstantBool) {
  751. // br(1 && X) -> br(X).
  752. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  753. }
  754. // If we have "X && 1", simplify the code to use an uncond branch.
  755. // "X && 0" would have been constant folded to 0.
  756. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  757. ConstantBool) {
  758. // br(X && 1) -> br(X).
  759. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  760. }
  761. // Emit the LHS as a conditional. If the LHS conditional is false, we
  762. // want to jump to the FalseBlock.
  763. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  764. ConditionalEvaluation eval(*this);
  765. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
  766. EmitBlock(LHSTrue);
  767. // Any temporaries created here are conditional.
  768. eval.begin(*this);
  769. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  770. eval.end(*this);
  771. return;
  772. }
  773. if (CondBOp->getOpcode() == BO_LOr) {
  774. // If we have "0 || X", simplify the code. "1 || X" would have constant
  775. // folded if the case was simple enough.
  776. bool ConstantBool = false;
  777. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  778. !ConstantBool) {
  779. // br(0 || X) -> br(X).
  780. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  781. }
  782. // If we have "X || 0", simplify the code to use an uncond branch.
  783. // "X || 1" would have been constant folded to 1.
  784. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  785. !ConstantBool) {
  786. // br(X || 0) -> br(X).
  787. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  788. }
  789. // Emit the LHS as a conditional. If the LHS conditional is true, we
  790. // want to jump to the TrueBlock.
  791. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  792. ConditionalEvaluation eval(*this);
  793. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
  794. EmitBlock(LHSFalse);
  795. // Any temporaries created here are conditional.
  796. eval.begin(*this);
  797. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  798. eval.end(*this);
  799. return;
  800. }
  801. }
  802. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  803. // br(!x, t, f) -> br(x, f, t)
  804. if (CondUOp->getOpcode() == UO_LNot)
  805. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
  806. }
  807. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  808. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  809. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  810. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  811. ConditionalEvaluation cond(*this);
  812. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
  813. cond.begin(*this);
  814. EmitBlock(LHSBlock);
  815. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
  816. cond.end(*this);
  817. cond.begin(*this);
  818. EmitBlock(RHSBlock);
  819. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
  820. cond.end(*this);
  821. return;
  822. }
  823. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  824. // Conditional operator handling can give us a throw expression as a
  825. // condition for a case like:
  826. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  827. // Fold this to:
  828. // br(c, throw x, br(y, t, f))
  829. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  830. return;
  831. }
  832. // Emit the code with the fully general case.
  833. llvm::Value *CondV = EvaluateExprAsBool(Cond);
  834. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  835. }
  836. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  837. /// specified stmt yet.
  838. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  839. CGM.ErrorUnsupported(S, Type);
  840. }
  841. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  842. /// variable-length array whose elements have a non-zero bit-pattern.
  843. ///
  844. /// \param baseType the inner-most element type of the array
  845. /// \param src - a char* pointing to the bit-pattern for a single
  846. /// base element of the array
  847. /// \param sizeInChars - the total size of the VLA, in chars
  848. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  849. llvm::Value *dest, llvm::Value *src,
  850. llvm::Value *sizeInChars) {
  851. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  852. = CGF.getContext().getTypeInfoInChars(baseType);
  853. CGBuilderTy &Builder = CGF.Builder;
  854. llvm::Value *baseSizeInChars
  855. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  856. llvm::Type *i8p = Builder.getInt8PtrTy();
  857. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  858. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  859. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  860. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  861. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  862. // Make a loop over the VLA. C99 guarantees that the VLA element
  863. // count must be nonzero.
  864. CGF.EmitBlock(loopBB);
  865. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  866. cur->addIncoming(begin, originBB);
  867. // memcpy the individual element bit-pattern.
  868. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  869. baseSizeAndAlign.second.getQuantity(),
  870. /*volatile*/ false);
  871. // Go to the next element.
  872. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
  873. // Leave if that's the end of the VLA.
  874. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  875. Builder.CreateCondBr(done, contBB, loopBB);
  876. cur->addIncoming(next, loopBB);
  877. CGF.EmitBlock(contBB);
  878. }
  879. void
  880. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  881. // Ignore empty classes in C++.
  882. if (getLangOpts().CPlusPlus) {
  883. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  884. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  885. return;
  886. }
  887. }
  888. // Cast the dest ptr to the appropriate i8 pointer type.
  889. unsigned DestAS =
  890. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  891. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  892. if (DestPtr->getType() != BP)
  893. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  894. // Get size and alignment info for this aggregate.
  895. std::pair<CharUnits, CharUnits> TypeInfo =
  896. getContext().getTypeInfoInChars(Ty);
  897. CharUnits Size = TypeInfo.first;
  898. CharUnits Align = TypeInfo.second;
  899. llvm::Value *SizeVal;
  900. const VariableArrayType *vla;
  901. // Don't bother emitting a zero-byte memset.
  902. if (Size.isZero()) {
  903. // But note that getTypeInfo returns 0 for a VLA.
  904. if (const VariableArrayType *vlaType =
  905. dyn_cast_or_null<VariableArrayType>(
  906. getContext().getAsArrayType(Ty))) {
  907. QualType eltType;
  908. llvm::Value *numElts;
  909. llvm::tie(numElts, eltType) = getVLASize(vlaType);
  910. SizeVal = numElts;
  911. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  912. if (!eltSize.isOne())
  913. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  914. vla = vlaType;
  915. } else {
  916. return;
  917. }
  918. } else {
  919. SizeVal = CGM.getSize(Size);
  920. vla = 0;
  921. }
  922. // If the type contains a pointer to data member we can't memset it to zero.
  923. // Instead, create a null constant and copy it to the destination.
  924. // TODO: there are other patterns besides zero that we can usefully memset,
  925. // like -1, which happens to be the pattern used by member-pointers.
  926. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  927. // For a VLA, emit a single element, then splat that over the VLA.
  928. if (vla) Ty = getContext().getBaseElementType(vla);
  929. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  930. llvm::GlobalVariable *NullVariable =
  931. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  932. /*isConstant=*/true,
  933. llvm::GlobalVariable::PrivateLinkage,
  934. NullConstant, Twine());
  935. llvm::Value *SrcPtr =
  936. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  937. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  938. // Get and call the appropriate llvm.memcpy overload.
  939. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  940. return;
  941. }
  942. // Otherwise, just memset the whole thing to zero. This is legal
  943. // because in LLVM, all default initializers (other than the ones we just
  944. // handled above) are guaranteed to have a bit pattern of all zeros.
  945. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  946. Align.getQuantity(), false);
  947. }
  948. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  949. // Make sure that there is a block for the indirect goto.
  950. if (IndirectBranch == 0)
  951. GetIndirectGotoBlock();
  952. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  953. // Make sure the indirect branch includes all of the address-taken blocks.
  954. IndirectBranch->addDestination(BB);
  955. return llvm::BlockAddress::get(CurFn, BB);
  956. }
  957. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  958. // If we already made the indirect branch for indirect goto, return its block.
  959. if (IndirectBranch) return IndirectBranch->getParent();
  960. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  961. // Create the PHI node that indirect gotos will add entries to.
  962. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  963. "indirect.goto.dest");
  964. // Create the indirect branch instruction.
  965. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  966. return IndirectBranch->getParent();
  967. }
  968. /// Computes the length of an array in elements, as well as the base
  969. /// element type and a properly-typed first element pointer.
  970. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  971. QualType &baseType,
  972. llvm::Value *&addr) {
  973. const ArrayType *arrayType = origArrayType;
  974. // If it's a VLA, we have to load the stored size. Note that
  975. // this is the size of the VLA in bytes, not its size in elements.
  976. llvm::Value *numVLAElements = 0;
  977. if (isa<VariableArrayType>(arrayType)) {
  978. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  979. // Walk into all VLAs. This doesn't require changes to addr,
  980. // which has type T* where T is the first non-VLA element type.
  981. do {
  982. QualType elementType = arrayType->getElementType();
  983. arrayType = getContext().getAsArrayType(elementType);
  984. // If we only have VLA components, 'addr' requires no adjustment.
  985. if (!arrayType) {
  986. baseType = elementType;
  987. return numVLAElements;
  988. }
  989. } while (isa<VariableArrayType>(arrayType));
  990. // We get out here only if we find a constant array type
  991. // inside the VLA.
  992. }
  993. // We have some number of constant-length arrays, so addr should
  994. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  995. // down to the first element of addr.
  996. SmallVector<llvm::Value*, 8> gepIndices;
  997. // GEP down to the array type.
  998. llvm::ConstantInt *zero = Builder.getInt32(0);
  999. gepIndices.push_back(zero);
  1000. uint64_t countFromCLAs = 1;
  1001. QualType eltType;
  1002. llvm::ArrayType *llvmArrayType =
  1003. dyn_cast<llvm::ArrayType>(
  1004. cast<llvm::PointerType>(addr->getType())->getElementType());
  1005. while (llvmArrayType) {
  1006. assert(isa<ConstantArrayType>(arrayType));
  1007. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  1008. == llvmArrayType->getNumElements());
  1009. gepIndices.push_back(zero);
  1010. countFromCLAs *= llvmArrayType->getNumElements();
  1011. eltType = arrayType->getElementType();
  1012. llvmArrayType =
  1013. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  1014. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  1015. assert((!llvmArrayType || arrayType) &&
  1016. "LLVM and Clang types are out-of-synch");
  1017. }
  1018. if (arrayType) {
  1019. // From this point onwards, the Clang array type has been emitted
  1020. // as some other type (probably a packed struct). Compute the array
  1021. // size, and just emit the 'begin' expression as a bitcast.
  1022. while (arrayType) {
  1023. countFromCLAs *=
  1024. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  1025. eltType = arrayType->getElementType();
  1026. arrayType = getContext().getAsArrayType(eltType);
  1027. }
  1028. unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
  1029. llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
  1030. addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
  1031. } else {
  1032. // Create the actual GEP.
  1033. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  1034. }
  1035. baseType = eltType;
  1036. llvm::Value *numElements
  1037. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1038. // If we had any VLA dimensions, factor them in.
  1039. if (numVLAElements)
  1040. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1041. return numElements;
  1042. }
  1043. std::pair<llvm::Value*, QualType>
  1044. CodeGenFunction::getVLASize(QualType type) {
  1045. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1046. assert(vla && "type was not a variable array type!");
  1047. return getVLASize(vla);
  1048. }
  1049. std::pair<llvm::Value*, QualType>
  1050. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1051. // The number of elements so far; always size_t.
  1052. llvm::Value *numElements = 0;
  1053. QualType elementType;
  1054. do {
  1055. elementType = type->getElementType();
  1056. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1057. assert(vlaSize && "no size for VLA!");
  1058. assert(vlaSize->getType() == SizeTy);
  1059. if (!numElements) {
  1060. numElements = vlaSize;
  1061. } else {
  1062. // It's undefined behavior if this wraps around, so mark it that way.
  1063. // FIXME: Teach -fcatch-undefined-behavior to trap this.
  1064. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1065. }
  1066. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1067. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1068. }
  1069. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1070. assert(type->isVariablyModifiedType() &&
  1071. "Must pass variably modified type to EmitVLASizes!");
  1072. EnsureInsertPoint();
  1073. // We're going to walk down into the type and look for VLA
  1074. // expressions.
  1075. do {
  1076. assert(type->isVariablyModifiedType());
  1077. const Type *ty = type.getTypePtr();
  1078. switch (ty->getTypeClass()) {
  1079. #define TYPE(Class, Base)
  1080. #define ABSTRACT_TYPE(Class, Base)
  1081. #define NON_CANONICAL_TYPE(Class, Base)
  1082. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1083. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1084. #include "clang/AST/TypeNodes.def"
  1085. llvm_unreachable("unexpected dependent type!");
  1086. // These types are never variably-modified.
  1087. case Type::Builtin:
  1088. case Type::Complex:
  1089. case Type::Vector:
  1090. case Type::ExtVector:
  1091. case Type::Record:
  1092. case Type::Enum:
  1093. case Type::Elaborated:
  1094. case Type::TemplateSpecialization:
  1095. case Type::ObjCObject:
  1096. case Type::ObjCInterface:
  1097. case Type::ObjCObjectPointer:
  1098. llvm_unreachable("type class is never variably-modified!");
  1099. case Type::Decayed:
  1100. type = cast<DecayedType>(ty)->getPointeeType();
  1101. break;
  1102. case Type::Pointer:
  1103. type = cast<PointerType>(ty)->getPointeeType();
  1104. break;
  1105. case Type::BlockPointer:
  1106. type = cast<BlockPointerType>(ty)->getPointeeType();
  1107. break;
  1108. case Type::LValueReference:
  1109. case Type::RValueReference:
  1110. type = cast<ReferenceType>(ty)->getPointeeType();
  1111. break;
  1112. case Type::MemberPointer:
  1113. type = cast<MemberPointerType>(ty)->getPointeeType();
  1114. break;
  1115. case Type::ConstantArray:
  1116. case Type::IncompleteArray:
  1117. // Losing element qualification here is fine.
  1118. type = cast<ArrayType>(ty)->getElementType();
  1119. break;
  1120. case Type::VariableArray: {
  1121. // Losing element qualification here is fine.
  1122. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1123. // Unknown size indication requires no size computation.
  1124. // Otherwise, evaluate and record it.
  1125. if (const Expr *size = vat->getSizeExpr()) {
  1126. // It's possible that we might have emitted this already,
  1127. // e.g. with a typedef and a pointer to it.
  1128. llvm::Value *&entry = VLASizeMap[size];
  1129. if (!entry) {
  1130. llvm::Value *Size = EmitScalarExpr(size);
  1131. // C11 6.7.6.2p5:
  1132. // If the size is an expression that is not an integer constant
  1133. // expression [...] each time it is evaluated it shall have a value
  1134. // greater than zero.
  1135. if (SanOpts->VLABound &&
  1136. size->getType()->isSignedIntegerType()) {
  1137. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1138. llvm::Constant *StaticArgs[] = {
  1139. EmitCheckSourceLocation(size->getLocStart()),
  1140. EmitCheckTypeDescriptor(size->getType())
  1141. };
  1142. EmitCheck(Builder.CreateICmpSGT(Size, Zero),
  1143. "vla_bound_not_positive", StaticArgs, Size,
  1144. CRK_Recoverable);
  1145. }
  1146. // Always zexting here would be wrong if it weren't
  1147. // undefined behavior to have a negative bound.
  1148. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1149. }
  1150. }
  1151. type = vat->getElementType();
  1152. break;
  1153. }
  1154. case Type::FunctionProto:
  1155. case Type::FunctionNoProto:
  1156. type = cast<FunctionType>(ty)->getResultType();
  1157. break;
  1158. case Type::Paren:
  1159. case Type::TypeOf:
  1160. case Type::UnaryTransform:
  1161. case Type::Attributed:
  1162. case Type::SubstTemplateTypeParm:
  1163. case Type::PackExpansion:
  1164. // Keep walking after single level desugaring.
  1165. type = type.getSingleStepDesugaredType(getContext());
  1166. break;
  1167. case Type::Typedef:
  1168. case Type::Decltype:
  1169. case Type::Auto:
  1170. // Stop walking: nothing to do.
  1171. return;
  1172. case Type::TypeOfExpr:
  1173. // Stop walking: emit typeof expression.
  1174. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1175. return;
  1176. case Type::Atomic:
  1177. type = cast<AtomicType>(ty)->getValueType();
  1178. break;
  1179. }
  1180. } while (type->isVariablyModifiedType());
  1181. }
  1182. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  1183. if (getContext().getBuiltinVaListType()->isArrayType())
  1184. return EmitScalarExpr(E);
  1185. return EmitLValue(E).getAddress();
  1186. }
  1187. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1188. llvm::Constant *Init) {
  1189. assert (Init && "Invalid DeclRefExpr initializer!");
  1190. if (CGDebugInfo *Dbg = getDebugInfo())
  1191. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1192. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1193. }
  1194. CodeGenFunction::PeepholeProtection
  1195. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1196. // At the moment, the only aggressive peephole we do in IR gen
  1197. // is trunc(zext) folding, but if we add more, we can easily
  1198. // extend this protection.
  1199. if (!rvalue.isScalar()) return PeepholeProtection();
  1200. llvm::Value *value = rvalue.getScalarVal();
  1201. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1202. // Just make an extra bitcast.
  1203. assert(HaveInsertPoint());
  1204. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1205. Builder.GetInsertBlock());
  1206. PeepholeProtection protection;
  1207. protection.Inst = inst;
  1208. return protection;
  1209. }
  1210. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1211. if (!protection.Inst) return;
  1212. // In theory, we could try to duplicate the peepholes now, but whatever.
  1213. protection.Inst->eraseFromParent();
  1214. }
  1215. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1216. llvm::Value *AnnotatedVal,
  1217. StringRef AnnotationStr,
  1218. SourceLocation Location) {
  1219. llvm::Value *Args[4] = {
  1220. AnnotatedVal,
  1221. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1222. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1223. CGM.EmitAnnotationLineNo(Location)
  1224. };
  1225. return Builder.CreateCall(AnnotationFn, Args);
  1226. }
  1227. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1228. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1229. // FIXME We create a new bitcast for every annotation because that's what
  1230. // llvm-gcc was doing.
  1231. for (specific_attr_iterator<AnnotateAttr>
  1232. ai = D->specific_attr_begin<AnnotateAttr>(),
  1233. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  1234. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1235. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1236. (*ai)->getAnnotation(), D->getLocation());
  1237. }
  1238. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1239. llvm::Value *V) {
  1240. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1241. llvm::Type *VTy = V->getType();
  1242. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1243. CGM.Int8PtrTy);
  1244. for (specific_attr_iterator<AnnotateAttr>
  1245. ai = D->specific_attr_begin<AnnotateAttr>(),
  1246. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
  1247. // FIXME Always emit the cast inst so we can differentiate between
  1248. // annotation on the first field of a struct and annotation on the struct
  1249. // itself.
  1250. if (VTy != CGM.Int8PtrTy)
  1251. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1252. V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
  1253. V = Builder.CreateBitCast(V, VTy);
  1254. }
  1255. return V;
  1256. }
  1257. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }