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